[英]Return values of array if in_array() returns true
我有一個多維度陣列
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
是存在這個多維數組中,因此否則返回false返回true,但我想要得到的值price
, sor_id
第一的位置的。 但是它僅返回1
或'0',因此如何返回整個數組或數組index
因此使用該數組或索引我可以獲取值。 或任何其他選項。
你快到了。 返回true,而不是true:
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.