【问题标题】:Finding a value in an associative array [duplicate]在关联数组中查找值[重复]
【发布时间】:2015-09-24 00:34:11
【问题描述】:

我有一个嵌套数组,我想知道如何在其中查找元素。

这是数组:

$test = [
    ['item_id' => 780, 'quantity' => 1],
    ['item_id' => 759, 'quantity' => 3],
    ['item_id' => 453, 'quantity' => 12]
];

我确实设法使用了foreaech 循环,但想知道是否有更好的方法?

foreach($test as $t) {
    if($t['item_id']==780) echo $t['quantity'];
}

【问题讨论】:

  • item_id 在数组中是唯一的吗?如果是,您可以修改数据结构,使其以该值为键,然后数量查找将简化为数组索引。

标签: php arrays


【解决方案1】:

如果数组已经排序,则可以在 O(log n) 时间内完成,但如果没有,则必须搜索所有元素直到找到它,即 O(n) 时间。如果数组未排序,我认为迭代它们是唯一的方法。如果存在对数组进行预排序的选项,它可能会更快。

编辑:如果可以更改数据结构,那么这将为更快的算法开辟很多可能性,但我认为这里不是这种情况。

【讨论】:

    【解决方案2】:

    递归使用 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 false;
    }
    
    $arr = array(array('item_id'=>2132,'quantity'=>1),array('item_id'=>759,'quantity'=>3),array('item_id'=>453,'quantity'=>12));
    echo in_array_r("2132", $arr) ? 'found' : 'not found';
    

    【讨论】:

      猜你喜欢
      • 2016-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-12
      • 2012-08-09
      • 2016-06-07
      • 1970-01-01
      相关资源
      最近更新 更多