php - 如何组合这两个 PHP 数组?

标签 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)

我想将它们组合成一个按图像权重排序的 id 数组。如果图像末尾没有附加权重。

这不是一个特别难的问题,但我的解决方案远非优雅,并且不禁想到必须有更好的方法来做到这一点。

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

问题:有更好的方法吗?

最佳答案

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

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

这是完整的过程。

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

关于php - 如何组合这两个 PHP 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3038025/

相关文章:

php - 依赖于 phpunit 似乎没有工作

使用常量代替字符串的 PHP 性能

objective-c - 从在 ARC 下包装第 3 方 C++ 对象的类返回 C 样式数组是否安全?

arrays - 在数组的数组上应用过滤器函数在 Scala 中返回异常

python - 使用二维数组创建西洋棋棋子 - Pygame

php - 如何在php中插入多维数组?

php - 添加到不同表时删除一行

php - 多级登录 codeigniter 未成功重定向

javascript - 如何使用钩子(Hook)更改数组的状态?

C语言中将一维数组复制为二维数组