我有一个多维数组,
Array
(
[0] => Array
(
[item_no] => 1.01
[sor_id] => 2
[selected_qty] => 7
[price] => 3
[type] => S
[form_name] => GSOR
[parent_id] => 89
)
[1] => Array
(
[item_no] => 1.03.03
[sor_id] => 7
[selected_qty] => 1
[price] => 50
[type] => S
[form_name] => GSOR
[parent_id] => 89
)
[2] => Array
(
[item_no] => 1.23
[sor_id] => 28
[selected_qty] => 6
[price] => 60
[type] => S
[form_name] => GSOR
[parent_id] => 89
)
[3] => Array
(
[item_no] => 6.03
[sor_id] => 64
[selected_qty] => 1
[price] => 50
[type] => S
[form_name] => GSOR
[parent_id] => 61
)
[4] => Array
(
[item_no] => 4.02
[sor_id] => 42
[selected_qty] => 1
[price] => 39
[type] => S
[form_name] => GSOR
[parent_id] => 40
)
)
我有一个递归函数,如果该值存在于多维数组中,则返回true,
递归in_array()函数,
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
// return $haystack;
// print_r($haystack);
}
}
return false;
}
实施例,
echo $item_2 = in_array_r("1.03.03", $selected_items_array) ? 'found' : 'not found';
所以,
item_no
=>此多维数组中存在1.03.03
,因此它返回true,否则返回false,
但我希望获得第一位置price
,sor_id
的值。
但它只返回1
或' 0'所以如何返回整个数组或数组index
所以使用该数组或索引我可以获取值。或任何其他选择。
答案 0 :(得分:2)
你快到了。而不是true,返回匹配元素的id:
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $key => $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return $key;
}
}
return false;
}
$matching_item = in_array_r("1.03.03", $selected_items_array);
echo $matching_item===false ? "not found" : " found at item ".$matching_item;