douwei1174 2019-07-14 18:00
浏览 77

如果PHP包含某些值,则创建数组

I have $fruits_arr:

Array
(
    [0] => Array
        (
            [id] => 213
            [fruit] => banana
        )

    [1] => Array
        (
            [id] => 438
            [fruit] => apple
        )

    [2] => Array
        (
            [id] => 154
            [fruit] => peach
        )
)

And $ids_arr:

Array ( 
  [0] => 213
  [1] => 154 
)

I want to recreate $fruits_arr to have only array items where id is equal to a value from $ids_arr. I also want to maintain the index/array order of $fruits_arr.

I'm using the following:

$selected_fruits = array();

foreach( $fruits_arr as $fruit ) :
    if ( in_array( $fruit['id'], $ids_arr ) ) :
        $selected_fruits[] = $fruit;
    endif;
endforeach;

print_r( $selected_fruits );

It seems to work but I am wondering if there is a shorter, better way to accomplish this in the latest PHP version.

  • 写回答

4条回答 默认 最新

  • dongnao6858 2019-07-14 18:18
    关注

    You could use array_filter to make it more concise, but it will not be much and could make your code less readable. If possible chose readability over length of code.

    $selected_fruits = array_filter($fruits_arr, function ($el) use ($ids_arr) {
        return in_array($el['id'], $ids_arr, true);
    });
    

    or you can wait for PHP 7.4 (due to come out at the end of the year) and use arrow functions.

    $selected_fruits = array_filter($fruits_arr, fn ($el) => in_array($el['id'], $ids_arr, true));
    

    Demo: https://3v4l.org/4UC41

    评论

报告相同问题?

悬赏问题

  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R