dsm0688 2016-09-14 09:41
浏览 54

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

I have arrays dishesand favorites. My goals is to add a field to the dishes array if a certain dish occurs in the favoritesone. This is what I have tried but it doesn't seem to be working since I get an empty array back.

$boundDishes = [];

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

Am I doing something wrong or is there a better way?

Any help is very much appreciated!

Many thanks in advance!!

  • 写回答

3条回答 默认 最新

  • drxp993551 2016-09-14 09:46
    关注

    To make this an answer, you are returning $boundGames but not adding anything to it so that's why it's empty, did you mean to add to $boundGames instead of $boundDishes in your loop as below?

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

    Alternatively, did you mean to return $boundDishes?

    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算