根据PHP数组的同一行中的另一个键值检索键值

时间:2017-10-03 18:50:48

标签: php arrays multidimensional-array array-filter array-column

我正在使用类似于此结构的索引PHP数组:

$result =   Array(
  [0] => Array([storepickup_id] => 3[sku] => 691294[inventory] => 33[reserve] => )
  [1] => Array([storepickup_id] => 3[sku] => 692284[inventory] => 3[reserve] => )
  [2] => Array([storepickup_id] => 3[sku] => 692289[inventory] => 4[reserve] => )
  [3] => Array([storepickup_id] => 3[sku] => 693510[inventory] => 8[reserve] => )
  [4] => Array([storepickup_id] => 3[sku] => 150893[inventory] => 2[reserve] => )
  [5] => Array([storepickup_id] => 3[sku] => 150906[inventory] => 4[reserve] => )
)

我试图使用预先构建的FOR EACH语句过滤上面的数组,如下所示:

<?php foreach ($_productCollection as $_product): ?>
    <?php
    echo "SKU: " . $_product->getSku();
    echo "INVENTORY: " . array_column($result, 'inventory', $_product->getSku());
<?php endforeach; ?>

因此,如果$ _product-getSku()得到691294,我想从PHP数组的相同索引/行中检索相应的“inventory”值。

FOR EACH中的上述array_column不起作用。我还尝试了一个基于array_filter的函数,它无法产生正确的结果:

<?php foreach ($_productCollection as $_product): ?>
  <?php
  function my_function($item_values)
  {
      if ($item_values = $_product->getSku())
      {
          return true;
      }
      return false;
  }
  $sku = $_product->getSku();
  print_r(array_filter($sku,"my_function"));
  ?>
<?php endforeach; ?>

使用上面的多维数组时是否有更好的方法?提前谢谢。

2 个答案:

答案 0 :(得分:2)

首先,您需要创建一个新数组,其索引/键包含sku,列/值包含来自$ result数组的库存。

$new_array = array_column($result, 'inventory', 'sku');

然后在循环中使用新数组

<?php foreach ($_productCollection as $_product): ?>
    <?php
    echo "SKU: " . $_product->getSku();
    echo "INVENTORY: " . $new_array[$_product->getSku()];
<?php endforeach; ?>

如果$ _product-getSku()得到691294,则Invetory将为33

答案 1 :(得分:1)

function getIndex($needle, $haystack, $array){
    foreach($array as $key => $value){
        if(is_array($value) && $value[$haystack] == $needle)
              return $key;
    }
    return null;
}

像这样使用:

$i = getIndex(691294, 'Sku', $array);
echo $array[$i]['inventory'];