Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine these two PHP arrays?

I have two arrays in php that are part of an image management system.

weighted_images A multidimensional array. Each sub array is an associative array with keys of 'weight' (for ordering by) and 'id' (the id of the image).

array(
    156 => array('weight'=>1, 'id'=>156),
    784 => array('weight'=>-2, 'id'=>784),
)

images This array is user input. It's an array of image ids.

array(784, 346, 748)

I want to combine them in to a single array of ids ordered by the weight of the image. If an image doesn't have a weight append to the end.

It's not a particularly hard problem however my solution is far from elegant and can't help thinking that there must be a better way to do this.

$t_images = array();
foreach ($weighted_images as $wi) {
  if ( in_array($wi['id'], $images) ) {
    $t_images[$wi['weight']] = $wi['id'];
  }
}
foreach ($images as $image) {
  if ( !$weighted_images[$image] ) {
    $t_images[] = $image;
  }
}
$images = $t_images;

Question: Is there a better way to do this?

like image 495
AnnanFay Avatar asked Dec 07 '25 09:12

AnnanFay


1 Answers

Schmalls is almost right, just missed the last step -

If an image doesn't have a weight append to the end.

Here is the full process.

$array = array_intersect_key($weighted_images, array_fill_keys($images, null));

uasort($array, function($a, $b) {
    if($a['weight'] == $b['weight']) return 0;
    return ($a['weight'] > $b['weight']) ? 1 : -1;
});

$array += array_diff_key($images, $weighted_images);
like image 144
Chase Finch Avatar answered Dec 10 '25 00:12

Chase Finch