PHP比较2个数组并在匹配时添加字段

时间:2016-09-14 09:41:53

标签: php arrays

我有数组dishesfavorites。我的目标是在dishes数组中出现某个菜肴时向favorites数组添加一个字段。这是我尝试过的,但它似乎没有工作,因为我得到一个空数组。

$boundDishes = [];

foreach ($dishes as $dish) {
    foreach ($favorites as $favorite) {
        if ($favorite == $dish) {
            $dishes['favorite'] = true;
            $boundDishes[] = $dish;
        }
    }
}
return $boundDishes;

我做错了什么还是有更好的方法?

非常感谢任何帮助!

非常感谢提前!!

3 个答案:

答案 0 :(得分:0)

要回答这个问题,您将返回 $ boundGames ,但不会向其添加任何内容,以便它为什么是空的,您是否要添加到您的循环中的$ boundGames 而非 $ boundDishes 如下所示?

$boundGames = [];

foreach($dishes as $dish) {
    foreach($favorites as $favorite) {
        if($favorite == $dish) {
            $dishes['favorite'] = true;
            $boundGames[] = $dishes;
        }
    }
}
return $boundGames;

或者,您的意思是return $boundDishes吗?

答案 1 :(得分:0)

<?php

$dishes =
[
    'chips',
    'hummus',
    'eggs',
    'ham'
];


$favourites =
[
    'spam',
    'hummus'
];

foreach($favourites as $favourite) {
    if(!in_array($favourite, $dishes)) {
        $dishes[] = $favourite;
    }
}

var_export($dishes);

输出:

array (
  0 => 'chips',
  1 => 'hummus',
  2 => 'eggs',
  3 => 'ham',
  4 => 'spam',
)

或者只是合并然后过滤唯一值:

$dishes = array_unique(array_merge($dishes, $favourites))

也许您只需要辅助功能:

$is_favourite = function($dish) use ($favourites) {
    return in_array($dish, $favourites);
};

echo $is_favourite('spam') ? 'They love spam!' : '';

答案 2 :(得分:0)

这是你的意思吗?

$boundDishes = [];

foreach ($dishes as $dish) {
    if (in_array($dish, $favourites)) {
        $boundDishes[] = $dish;
    }
}
return $boundDishes;