PHP按值合并数组 [英] PHP merge arrays by value

查看:42
本文介绍了PHP按值合并数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这很容易用 foreach,然后是 while->list 等过程来完成,(我已经完成了),但是我觉得我的代码有点脏,看起来不是最好的解决方案......我希望使用本机 PHP 数组函数来执行以下操作:

我有两个看起来像这样的数组:

<前>[0](数组)#2[等级]"579"[编号]1"[1](数组)#4[等级]"251"[编号] "2"[0](数组)#2[尺寸]"S"[状态]A"[编号]1"[1](阵列)#15[尺寸]"L"[状态]A"[编号] "2"

因此,我需要如下内容:

<前>[0](数组)#2[尺寸]"S"[状态]A"[编号]1"[等级]"579"[1](数组)#2[尺寸]"L"[状态]A"[编号] "2"[等级]"251"

有没有一种方法可以合并具有 id 值(或其他)的两个数组,而无需进入无穷无尽的 foreach 集合?

解决方案

使用 array_merge_recursive()

$array = array_merge_recursive($array1, $array2);

或者自己做一个函数(可能会更快)

function my_array_merge(&$array1, &$array2) {$result = Array();foreach($array1 as $key => &$value) {$result[$key] = array_merge($value, $array2[$key]);}返回 $result;}$array = my_array_merge($array1, array2);print_r($array);

I know this is quite easily accomplished with a foreach, then a while->list, etc procedure, (I have already accomplished it), however I sense that my code is a bit dirty and it doesn't look like the best solution... I'm looking to use native PHP array functions to do the following:

I have two arrays that look like this:

[0] (Array)#2
  [rank] "579"
  [id] "1"
[1] (Array)#4
  [rank] "251"
  [id] "2"

[0] (Array)#2
  [size] "S"
  [status] "A"
  [id] "1"
[1] (Array)#15
  [size] "L"
  [status] "A"
  [id] "2"

And I need as a result something like the following:

[0] (Array)#2
  [size] "S"
  [status] "A"
  [id] "1"
  [rank] "579"

[1] (Array)#2
  [size] "L"
  [status] "A"
  [id] "2"
  [rank] "251"

Is there a way to be able to merge two arrays with the id value (or ay other) without going into a endless set of foreachs?

解决方案

Use array_merge_recursive()

$array = array_merge_recursive($array1, $array2);

or make your own function (it may be faster)

function my_array_merge(&$array1, &$array2) {
    $result = Array();
    foreach($array1 as $key => &$value) {
        $result[$key] = array_merge($value, $array2[$key]);
    }
    return $result;
}
$array = my_array_merge($array1, array2);
print_r($array);

这篇关于PHP按值合并数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆