это мой массив
массив ( [category_id] => 4 [parent_id] => 3 [name] => Категория по умолчанию [is_active] => 1 [position] => 4 [уровень] => 2 [children] => Массив ( [0] => Массив ( [category_id] => 122 [parent_id] => 4 [name] => Root [is_active] => 1 [position] => 1 [уровень] => 3 [children] => Массив ( [0] => Массив ( [category_id] => 123 [parent_id] => 122 [name] => Одежда [is_active] => 1 [position] => 1 [уровень] => 4 [children] => Массив ( [0] => Массив ( [category_id] => 124 [parent_id] => 123 [name] => Мужская одежда [is_active] => 1 [position] => 1 [уровень] => 5 [children] => Массив ( [0] => Массив ( [category_id] => 125 [parent_id] => 124 [name] => Полос тройники [is_active] => 1 [position] => 1 [уровень] => 6 [children] => Массив ( ) ) ) ) ) ) [1] => Массив ( [category_id] => 126 [parent_id] => 122 [name] => Мода [is_active] => 1 [position] => 2 [уровень] => 4 [children] => Массив ( [0] => Массив ( [category_id] => 127 [parent_id] => 126 [name] => Обувь [is_active] => 1 [position] => 1 [уровень] => 5 [children] => Массив ( [0] => Массив ( [category_id] => 128 [parent_id] => 127 [name] => Женщины [is_active] => 1 [position] => 1 [уровень] => 6 [children] => Массив ( [0] => Массив ( [category_id] => 129 [parent_id] => 128 [name] => Квартиры [is_active] => 1 [position] => 1 [уровень] => 7 [children] => Массив ( ) ) ) ) ) ) ) ) ) ) ) )
а также
что я хочу сделать, это то, что:
написать функцию
foo($find,$array){
//do some coding to search in the array
return $category_id;//category id of the coresponding matched name in array
}
например :
foo("Clothing",$array);
вернется 18
foo("Men Clothing",$array)
вернется 19
и так далее
Ты можешь использовать recursion
, Пример здесь ..
function getId($arr, $val){
if(is_array($arr)){
if(isset($arr['name']) && trim($arr['name']) == trim($val)){
return isset($arr['category_id']) ? $arr['category_id'] : 'Not found';
}
foreach($arr as $values){
if(is_array($values)){
return getId($values, $val);
}
}
}
}
$val = getId($arr, 'Polos & Tees');
echo $val; //output 20
Это решение с рекурсией:
function foo($find, $array) {
if( $array['name'] == $find ) {
return $array['category_id'];
}
if( empty($array['children']) ) {
return null;
}
foreach($array['children'] as $child) {
$result = foo($find, $child);
if( $result !== null ) {
return $result;
}
}
return null;
}
echo foo('Default Category', $array), "\n"; // 4
echo foo('Root', $array), "\n"; // 122
echo foo('Clothing', $array), "\n"; // 123
echo foo('Men Clothing', $array), "\n"; // 124
echo foo('Polos & Tees', $array), "\n"; // 125
echo foo('Fashion', $array), "\n"; // 126
echo foo('Footwear', $array), "\n"; // 127
echo foo('Women', $array), "\n"; // 128
echo foo('Flats', $array), "\n"; // 129