phparraysassociative-arraystring-parsingdelimited

Parse a string with 3 delimiters and return the keys which contain a qualifying value


This is my $data variable:

cv = 1,2,3,4,5:::cpt = 4,5 ...

Now I need some function, where I can add the number as param (number will be $data number value).

for example.

function getPermission($id) {

... return $something;
}

Then if I call the function like: echo getPermission(4); it'll print out the data 'keys' where the 4 will be inside, as a value.

So, to be clear:

if I call the function like this:

echo getPermission(4); output will be "cv" and "cpt".

but if I call it this way:

echo getPermission(1);

it'll only output "cv" because number (1) is located in the cv key.


Solution

  • $str = 'cv = 1,2,3,4,5:::cpt = 4,5';
    $tmp = explode(':::', $str);
    $data = array();
    foreach ($tmp as $arr) {
        $tokens = explode(' = ', $arr);
        $data[$tokens[0]] = explode(',', $tokens[1]);
    }
    
    print_r(getPermission(4, $data));
    print_r(getPermission(1, $data));
    
    function getPermission($id, $data) {
        $out = array();
        foreach ($data as $key => $arr) {
            if (in_array($id, $arr)) $out[] = $key;
        }
        return $out;
    }