Antonio Morales
Antonio Morales

Reputation: 1074

Extract array index and merge the item in other array PHP

I have this array $all_designs_from_select_articles in PHP. Each index contains the objects 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:

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? I´m using PHP7 and the framework laravel 5.2

Upvotes: 0

Views: 37

Answers (2)

Matt Raines
Matt Raines

Reputation: 4218

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.

Upvotes: 1

Scott Morgan
Scott Morgan

Reputation: 111

I haven't tested this code but it should be as simple as just using array_merge().

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

Upvotes: 0

Related Questions