简体   繁体   中英

Merge two arrays, one array each 5 key

I'm trying to merge 2 arrays but I would like to add my first array each 5 key.

$main_list = array(data-main-1, data-main-2, data-main-3, data-main-4, data-main-5, data-main-6, data-main-7, data-main-8, data-main-9, data-main-10); 
$programme_list = array(data-programme-1, data-programme-2, data-programme-3);

$complete_list = array(data-programme-1, data-main-1, data-main-2, data-main-3, data-main-4, data-programme-2, data-main-5, data-main-6, data-main-7, data-main-8, programme-2, data-main-9, data-main-10)

Example :

  • data-programme-1
  • data-main-1
  • data-main-2
  • data-main-3
  • data-main-4
  • data-programme-2
  • data-main-5
  • data-main-6
  • data-main-7
  • data-main-8
  • data-programme-3 .....

I wrote this but with odd/even system (all works fine but not the solution for me) :

$main_list = get_field('home_list_main');
$programme_list = get_field('home_list_programme');

$complete_list = array();

foreach($main_list as $key => $value) {
    $complete_list[] = $value;

    if (isset($programme_list[$key])) {
        $complete_list[] = $programme_list[$key];
    }
}

echo $complete_list;

How can I do please ?

If you first split the main list into 5's (using array_chunk() in this example), you can then add the programme followed by the corresponding chunk...

$complete_list = [];
$mainChunk = array_chunk($main_list, 5);
foreach ( $programme_list as $key => $programme )   {
    $complete_list[] = $programme;
    $complete_list = array_merge($complete_list, $mainChunk[$key] ?? []);
}

Using $mainChunk[$key] ?? [] $mainChunk[$key] ?? [] in case their isn't data for this item and just default it to an empty array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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