How to combine these two PHP arrays ?

Posted by Annan on Stack Overflow See other posts from Stack Overflow or by Annan
Published on 2010-06-14T14:24:23Z Indexed on 2010/06/14 15:22 UTC
Read the original article Hit count: 223

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about php

Related posts about array