Asked  1 Year ago    Answers:  5   Viewed   17 times

How can I merge these two array together?

Array
(
[0] => Array
    (
        [id] => 5
        [cnt] => 14
    )

[1] => Array
    (
        [id] => 8
        [cnt] => 2
    )

)

Array
(
    [0] => Array
        (
            [id] => 8
            [binding] => hardcover
        )

    [1] => Array
        (
            [id] => 5
            [binding] => softcover
        )
)

The expected result is:

Array
    (
        [0] => Array
            (
                [id] => 5
                [binding] => softcover
                [cnt] => 14
            )

        [1] => Array
            (
                [id] => 8
                [binding] => hardcover
                [cnt] => 2
            )

    )

The merge of these two array should happen on the [id] value and not on any sort of the array. How can I do this with php in a fast way?

 Answers

1
$output = array();

$arrayAB = array_merge($arrayA, $arrayB);
foreach ( $arrayAB as $value ) {
  $id = $value['id'];
  if ( !isset($output[$id]) ) {
    $output[$id] = array();
  }
  $output[$id] = array_merge($output[$id], $value);
}

var_dump($output);

Optionally if you want to reset output's keys, just do:

$output = array_values($output);
Thursday, April 1, 2021
 
2

You can just do a nested loop and check if the id values match, then add title to $first (or name to $second)

foreach($first as $key => $value){
    foreach($second as $value2){
        if($value['id'] === $value2['id']){
            $first[$key]['title'] = $value2['title'];
        }               
    }
}
Thursday, April 1, 2021
 
2

The uasort() function allows you to specify a callback function, which will be responsible of doing the comparison between two elements -- so, should do just well, if you implement the proper callback function.

Here, you'd have to implement a callback function that will receive two arrays -- and compmare the age item :

function callback($a, $b) {
  if ($a['age'] > $b['age']) {
    return 1;
  } else if ($a['age'] < $b['age']) {
    return -1;
  }
  return 0;
}


Using that function in the following portion of code :

$arr = array(
    'ted' => array( 'age' => 27 ),
    'bob' => array( 'age' => 18 ),
    'jay' => array( 'age' => 24 )
);

uasort($arr, 'callback');
var_dump($arr);

You would get you this resulting array :

array
  'bob' => 
    array
      'age' => int 18
  'jay' => 
    array
      'age' => int 24
  'ted' => 
    array
      'age' => int 27
Thursday, April 1, 2021
 
3

This is what I would do:

<?php
$promo = Array (
   Array ('insertDate' => '2014-11-10 11:23:08', 'keyword' => 'promo', 'mediaClass' => 'image', 'mediaURL' => 'http://image2.jpg', 'promoURL' => 'http://www.google.com'),
   Array ('insertDate' => '2014-11-10 11:23:38', 'keyword' => 'promo', 'mediaClass' => 'image', 'mediaURL' => 'http://image5.jpg', 'promoURL' => 'http://www.google.com')
 );

$media = Array (
  Array ('insertDate' => '2014-11-10 11:22:58', 'keyword' => 'standard', 'mediaClass' => 'image', 'mediaURL' => 'http://image1.jpg', 'promoURL' => '', ),
  Array ('insertDate' => '2014-11-10 11:23:18', 'keyword' => 'standard', 'mediaClass' => 'image', 'mediaURL' => 'http://image3.jpg', 'promoURL' => '', ),
  Array ('insertDate' => '2014-11-10 11:23:28', 'keyword' => 'standard', 'mediaClass' => 'image', 'mediaURL' => 'http://image4.jpg', 'promoURL' => '', ),
  Array ('insertDate' => '2014-11-10 11:23:48', 'keyword' => 'standard', 'mediaClass' => 'image', 'mediaURL' => 'http://image6.jpg', 'promoURL' => '', )
);

//sort the promo in random order. This ensures they go into media in random order
shuffle($promo);

//get random keys to insert the promo image before
$randKeys = array_rand($media, count($promo));
//sort by the random key value in reverse. By inserting in reverse order,
//we won't have an issue with needing to increment keys to prevent two promo
//images ending up next to each other. Also, this is why we shuffle the promo
//array above, so the promo images go in random order because this is no longer random.
rsort($randKeys);

//loop over the random keys and insert the next promo image before each key
foreach($randKeys as $key){
    //get the first promo image and remove it
    $promoImage = array_shift($promo);
    //splice the promo image into the media array
    array_splice($media, $key, 0, array($promoImage));
}

//display
print_r($media);

Only thing to note is that both my media and promo arrays are numeric index based starting at zero and contiguous which is default for an array and not like the arrays you posted where they 1 and 4 keys are removed from the media array.

Saturday, May 29, 2021
 
tplaner
 
4

By assigning temporary keys, you can determine whether you are dealing with the first occurrence or not and then use the appropriate technique to either store the whole subarray or merely add value to the price element of the subarray.

Code: (Demo)

$to_account = [
  [ 'account' => 251234567890, 'price' => 83 ],
  [ 'account' => 251234567890, 'price' => 27 ],
  [ 'account' => 251234564526, 'price' => 180 ],
  [ 'account' => 251234567890, 'price' => 40 ]
];

foreach ($to_account as $row) {
    if (!isset($result[$row['account']])) {
        $result[$row['account']] = $row;
    } else {
        $result[$row['account']]['price'] += $row['price'];
        // imitate the above line if there was another column to sum
    }
}
var_export($result);

Output:

array (
  251234567890 => 
  array (
    'account' => 251234567890,
    'price' => 150,
  ),
  251234564526 => 
  array (
    'account' => 251234564526,
    'price' => 180,
  ),
)

This method does not bother to overwrite redundant account element values. To reindex the output array, merely call array_values() on it.

Saturday, May 29, 2021
 
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :