Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am having 2 arrays and i have to merge that arrays with similar values. i tried for each and basic functions of php for array merging but not getting proper result.

i tried below thing but it wont work for me as i am having multiple data in second array. as you can see in child array i am having multiple records and i want to keep that together inside base array.

    $base= [
        ['id' => 1],
        ['id' => 2],
        ['id' => 3],
        ['id' => 4],
    ];
    
    $child = [
        ['id' => 1, 'size' => 'SM'],
        ['id' => 1, 'size' => 'LK'],
        ['id' => 2, 'size' => 'XL'],
        ['id' => 4, 'size' => 'LG'],
        ['id' => 3, 'size' => 'MD'],
    ];  
    
    foreach(array_merge($base, $child) as $el){
        $merged[$el['id']] = ($merged[$el['id']] ?? []) + $el;
    }
    
    Output :
    array (
      1 => 
      array (
        'id' => 1,
        'size' => 'SM',
      ),
      2 => 
      array (
        'id' => 2,
        'size' => 'XL',
      ),
      3 => 
      array (
        'id' => 3,
        'size' => 'MD',
      ),
      4 => 
      array (
        'id' => 4,
        'size' => 'LG',
      ),
    )

desired output :

array (
  1 => 
  array (
    'id' => 1,
    1 => array('size' => 'SM'),
    2 => array('size' => 'LK'),
  ),
  2 => 
  array (
    'id' => 2,
    1 => array('size' => 'XL'),
  ),
  3 => 
  array (
    'id' => 3,
    1 => array('size' => 'MD'),
  ),
  4 => 
  array (
    'id' => 4,
    1 => array('size' => 'LG'),
  ),
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
146 views
Welcome To Ask or Share your Answers For Others

1 Answer

Because your array $child have same key id value, and every you save the array, it always destroyed old array with same key id.

Here the working code :

<?php

$base= [
    ['id' => 1],
    ['id' => 2],
    ['id' => 3],
    ['id' => 4],
];

$child = [
    ['id' => 1, 'size' => 'SM'],
    ['id' => 1, 'size' => 'LK'],
    ['id' => 2, 'size' => 'XL'],
    ['id' => 4, 'size' => 'LG'],
    ['id' => 3, 'size' => 'MD'],
];  
foreach(array_merge($base, $child) as $el){
    if(!isset($el['size'])){ // $base doesn't have 'size' key
        $merged[$el['id']] = []; // fill with empty array 
    }else{
        $merged[$el['id']][] = $el;
    }
    // bellow code is for start array index from 1 instead of 0
    array_unshift($merged[$el['id']],"");
    unset($merged[$el['id']][0]);
}
print_r($merged);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...