简体   繁体   English

提取数组索引并将其合并到其他数组PHP中

[英]Extract array index and merge the item in other array PHP

I have this array $all_designs_from_select_articles in PHP. 我在PHP中有这个数组$ all_designs_from_select_articles Each index contains the objects Design: 每个索引都包含对象Design:

array:7 [▼
  0 => array:12 [▼
    0 => Design {#297 ▶}
    1 => Design {#298 ▶}
    2 => Design {#299 ▶}
    3 => Design {#300 ▶}
    4 => Design {#301 ▶}
    5 => Design {#302 ▶}
    6 => Design {#303 ▶}
    7 => Design {#304 ▶}
    8 => Design {#305 ▶}
    9 => Design {#306 ▶}
    10 => Design {#307 ▶}
    11 => Design {#308 ▶}
  ]
  1 => array:15 [▼
    0 => Design {#309 ▶}
    1 => Design {#310 ▶}
    2 => Design {#311 ▶}
    3 => Design {#312 ▶}
    4 => Design {#313 ▶}
    5 => Design {#314 ▶}
    6 => Design {#315 ▶}
    7 => Design {#316 ▶}
    8 => Design {#317 ▶}
    9 => Design {#318 ▶}
    10 => Design {#319 ▶}
    11 => Design {#320 ▶}
    12 => Design {#321 ▶}
    13 => Design {#322 ▶}
    14 => Design {#323 ▶}
  ]

]

But I want an array with all Design keys combined, like this: 但是我想要一个包含所有设计键的数组,如下所示:

array:26 [▼

 0 => Design {#297 ▶}
 1 => Design {#298 ▶}
 2 => Design {#299 ▶}
 3 => Design {#300 ▶}
 4 => Design {#301 ▶}
 5 => Design {#302 ▶}
 6 => Design {#303 ▶}
 7 => Design {#304 ▶}
 8 => Design {#305 ▶}
 9 => Design {#306 ▶}
 10 => Design {#307 ▶}
 11 => Design {#308 ▶}

 12 => Design {#309 ▶}
 13 => Design {#310 ▶}
 14 => Design {#311 ▶}
 15 => Design {#312 ▶}
 16 => Design {#313 ▶}
 17 => Design {#314 ▶}
 18 => Design {#315 ▶}
 19 => Design {#316 ▶}
 20 => Design {#317 ▶}
 21 => Design {#318 ▶}
 22 => Design {#319 ▶}
 23 => Design {#320 ▶}
 24 => Design {#321 ▶}
 25 => Design {#322 ▶}
 26 => Design {#323 ▶}
 ...
 etc
]

And this is my query to my API and get the first array values: 这是我对API的查询,并获取第一个数组值:

foreach ($search_articles as $article) {

                $all_designs_from_select_articles[] = ApiDesign::getList([
                    'article_id' => $article,
                    'visibility' => 'ALL',
                    'order' => '-POPULARITY,NAME',
                    'lang' => 'multi,es',
                ]);
            }

Is there a function in PHP to do this? PHP中是否有功能可以做到这一点? I´m using PHP7 and the framework laravel 5.2 我正在使用PHP7和laravel 5.2框架

You could merge the subarrays together after the fact with 您可以在事实发生之后将子数组合并在一起

$all_designs_from_select_articles = array_reduce(
    $all_designs_from_select_articles, "array_merge", []);

Or during the creation of the array: 或在创建数组期间:

foreach ($search_articles as $article) {
    $all_designs_from_select_articles = array_merge(
        $all_designs_from_select_articles,
        ApiDesign::getList(...));
}

I think I'd prefer the latter approach, but it's a marginal preference. 我认为我更喜欢后一种方法,但这是一个边际偏好。

我没有测试此代码,但它应该像使用array_merge()一样简单。

$newArray = array_merge($array[0], $array[1]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM