【问题标题】:Search in multidimensional array and return result without support variable在多维数组中搜索并返回不支持变量的结果
【发布时间】:2018-12-19 09:57:01
【问题描述】:

我有 2 个数组:

$fruits = array(
    'Apple' => array('id' => 1),
    'Banana' => array('id' => 2),
    'Peach' => array('id' => 3)
);
$carts = array(
    'Olivia' => array(51, 3, 2),
    'Harry' => array(312, 314, 10),
    'Charlie' => array(1, 314, 626)
);

如果购物车中有一些水果 id,我想写一些东西。我有这个代码,它的工作。

foreach ($carts as $cart) {
    $boughtFruit = false;
    foreach ($fruits as $fruit) {
        if (in_array($fruit['id'], $cart)) {
            echo "Fruit <br>";
            $boughtFruit = true;
            break;
        }
    }
    if(!$boughtFruit){
        echo "No Fruit <br>";
    } 
}

返回:

Fruit
No fruit
Fruit

我不喜欢我的解决方案,因为我需要使用支持变量 $boughtFruit 和 2 个 foreach。

您能否建议我使用PHP 函数(如果存在)和不使用$boughtFruit 的相同代码?

【问题讨论】:

    标签: php arrays loops multidimensional-array


    【解决方案1】:

    您不需要内部循环,而是使用array_intersect() 在数组中查找相同的值。

    $fru = array_column($fruits, "id");
    foreach ($carts as $cart) {
        echo count(array_intersect($cart, $fru)) ? "Fruit <br>" : "No Fruit <br>";
    }
    

    检查结果在demo


    如果你想得到匹配水果的名字,使用这个代码

    $fru = array_map(function($item){return $item['id'];}, $fruits);
    foreach ($carts as $cart) {
        $find = array_intersect($cart, $fru);
        if (count($find)){
            $result = implode(", ", array_map(function($item) use($fru){
                return array_search($item, $fru);
            }, $find));
            echo "Fruit ({$result})\n";
        } else
            echo "No Fruit \n";
    }
    

    输出:

    Fruit (Peach, Banana)
    No Fruit 
    Fruit (Apple)
    

    demo查看结果

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-26
      • 1970-01-01
      • 2014-04-16
      • 1970-01-01
      • 2013-08-29
      • 2014-11-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多