Reputation: 3715
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.
Upvotes: -1
Views: 948
Reputation: 47864
If this task was purely about parsing the input string to a 2d arrays, you'd just need to convert the triple-colons to newlines, parse the ini string, then csv-parse the array.
var_export(
array_map(
'str_getcsv',
parse_ini_string(
str_replace(':::', "\n", $data)
)
)
);
But then to craft a userland function to return all keys where the passed in integer is found in the subarray would take more iterations.
If you want a direct technique to return strings which relate to number sets containing the passed in integer, then preg_match_all()
can be ideal.
Match the label word, then lookahead for the whole qualifying number. Demo
define('PERMS', 'cv = 1,2,3,4,5:::cpt = 4,5:::foo = 33');
function getPermission(int $id): array {
preg_match_all("/\w+(?= = [^:]*\b$id\b)/", PERMS, $m);
return $m[0] ?? [];
}
// run 7 tests
var_export(
array_map(
'getPermission',
range(0, 6)
)
);
Output:
array (
0 =>
array (
),
1 =>
array (
0 => 'cv',
),
2 =>
array (
0 => 'cv',
),
3 =>
array (
0 => 'cv',
),
4 =>
array (
0 => 'cv',
1 => 'cpt',
),
5 =>
array (
0 => 'cv',
1 => 'cpt',
),
6 =>
array (
),
)
Upvotes: 0
Reputation: 7525
$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;
}
Upvotes: 4