【问题标题】:Return values of array if in_array() returns true如果 in_array() 返回 true,则返回数组的值
【发布时间】:2018-01-04 07:07:13
【问题描述】:

我有一个多维数组,

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,所以使用该数组或索引我可以获取值。或任何其他选择。

【问题讨论】:

  • 数据从何而来?如果它是一个数据库,您可能最好使用查询。

标签: php arrays


【解决方案1】:

你快到了。而不是 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;

【讨论】:

  • 哦。太感谢了。太好了,效果很好。如果可能的话,我会给你 100 票。 3 小时后我就被困在里面了 ;)
猜你喜欢
  • 1970-01-01
  • 2016-02-17
  • 2013-05-23
  • 1970-01-01
  • 1970-01-01
  • 2013-07-21
  • 1970-01-01
  • 2014-07-07
  • 1970-01-01
相关资源
最近更新 更多