Answer the question
In order to leave comments, you need to log in
How to find a value in a multidimensional associative array and display an array of data by php keys?
Good afternoon! There is a multidimensional associative array with data with different levels of nesting. Roughly like this:
Array
(
[0] => Array
(
[name1] => FRUITS
[name2] => 50
[name3] => SHTUKA
[name4] => 90
[name5] => RUR
[name6] => Array
(
[0] => Array
(
[name1] => APPLE
[name2] => 30
[name3] => SHTUKA
[name4] => 80
[name5] => RUR
[name6] => Array
(
[0] => Array
(
[name1] => ANTONOVKA
[name2] => 20
[name3] => SHTUKA
[name4] => 70
[name5] => RUR
[name6] =>
[name7] =>
)
[1] => Array
(
[name1] => ZIMNIE
[name2] => 10
[name3] => SHTUKA
[name4] => 65
[name5] => RUR
[name6] =>
[name7] =>
)
)
[name7] =>
)
[name7] =>
)
$result = array(
[0] => ANTONOVKA
[1] => 20
[2] => SHTUKA
[3] => 70
[4] => RUR
)
function findArray ($ar, $findValue, $executeKeys)
function findArray ($ar, $findValue, $executeKeys){
$result = array();
foreach ($ar as $k => $v) {
if (is_array($ar[$k])) {
$second_result = findArray ($ar[$k], $findValue, $executeKeys);
$result = array_merge($result, $second_result);
continue;
}
if ($v === $findValue) {
foreach ($executeKeys as $val){
$result[] = $ar[$val];
}
}
}
return $result;
}
Answer the question
In order to leave comments, you need to log in
Decision
function findArray ($ar, $findValue, $executeKeys){
$result = array();
foreach ($ar as $k => $v) {
if (is_array($ar[$k])) {
$second_result = findArray ($ar[$k], $findValue, $executeKeys);
$result = array_merge($result, $second_result);
continue;
}
if ($v === $findValue) {
foreach ($executeKeys as $val){
$result[] = $ar[$val];
}
}
}
return $result;
}
There is one correct word in the text - "recursively". So write a recursive function. The input is an array, the output is a new array, inside foreach and, if necessary, RECURSION.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question