如何组合这两个PHP数组?

时间:2010-06-14 14:24:23

标签: php arrays multidimensional-array

我在php中有两个数组,它们是图像管理系统的一部分。

weighted_images 多维数组。每个子数组都是一个关联数组,其键为'weight'(用于排序)和'id'(图像的id)。

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

images 此数组是用户输入。这是一组图像ID。

array(784, 346, 748)

我想将它们组合成按图像权重排序的单个数组。如果图像没有重量附加到最后。

这不是一个特别难的问题,但是我的解决方案远非优雅,并且不禁认为必须是更好的方法。

$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;

问题:有更好的方法吗?

5 个答案:

答案 0 :(得分:1)

Schmalls几乎是对的,只是错过了最后一步 -

  

如果图像没有重量   追加到最后。

这是完整的过程。

$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);

答案 1 :(得分:0)

<?php
$weights = array(
    156 => array('weight'=>1, 'id'=>156),
    784 => array('weight'=>-2, 'id'=>784),
);

$selected = array(784, 346, 748);

$selectedWeights = array();
foreach ($selected as $id)
{
    $weight = 0;
    if (isset($weights[$id]))
    {
        $weight = $weights[$id]['weight'];
    }
    $selectedWeights[$id] = $weight;
}
asort($selectedWeights);

print_r($selectedWeights);
?>

答案 2 :(得分:0)

如果我很了解你:

$data = array(
156 => array('weight'=>1, 'id'=>156),
784 => array('weight'=>-2, 'id'=>784),
);
$ids = array(156, 784, 431);


function compare_weight($item1, $item2) {
    return $item1['weight'] > $item2['weight'] ? 1 : -1;
}

uashort($data, 'compare_weight');

foreach($ids as $id)
    $data += array($id => array('weight'=>null, 'id'=>$id) );

答案 3 :(得分:0)

您可以轻松获得数组的交集:

$selected_images = array_intersect_key($weighted_images, array_fill_keys($images, null))

array_fill_keys函数使用$images数组作为键,使用null作为每个键的值。由于我们使用键(array_intersect_key)与数组相交,因此除了第一个数组之外,任何数组的值都无关紧要。

然后你可以使用回调函数按重量进行排序,如Skirmantas建议的那样:

function cmp_weight($a, $b)
{
    if ($a['weight'] == $b['weight']) {
        return 0;
    }

    return (($a['weight'] > $b['weight']) ? 1 : -1;
}

$images = uasort($selected_images, 'cmp_weight');

如果您使用的是PHP 5.3,则可以使用匿名函数:

$images = uasort($selected_images, function($a, $b)
{
    if ($a['weight'] == $b['weight']) {
        return 0;
    }

    return (($a['weight'] > $b['weight']) ? 1 : -1;
})

答案 4 :(得分:0)

我会开始重新思考 $ weighted_images 数组。像这样的东西,其中键是ID,值是重量,可能就足够了:

$weighted_images = array(
  156 => 1,
  784 => -2,
);
$images = array(156, 784, 431);

然后只做一些排序,并确保你拥有阵列中的所有图像。

// Images (with weight) ordered
asort($weighted_images);

// Check all images and add at the end the ones with no weight, with null value
foreach ($images as $id) {
  if (!array_key_exists($id, $weighted_images)) {
    $weighted_images[$id] = null;
  }
}

就是这样。

相关问题