Home > Backend Development > PHP Tutorial > php 合并多维数组问题

php 合并多维数组问题

WBOY
Release: 2016-06-06 20:38:51
Original
1053 people have browsed it

有2个数组

<code>$array1 =[
[0]=>
  array(3) {
    ["id"]=> "1",
    ["uid"]=>'123',
    ["status"]=>'0'
[1]=>
  array(3) {
    ["id"]=> "2",
    ["uid"]=>'321',
    ["status"]=>'1'
]
$array2 =[
[0]=>
  array(2) {
    ["uid"]=> "123",
    ["name"]=>'张三'
[1]=>
  array(2) {
    ["uid"]=> "321",
    ["name"]=>'李四'
]
</code>
Copy after login
Copy after login

我在循环输出array1的时候。如何把uid替换成array2中的name?

<code>foreach($array1 as $item) {
  $item['status']= $item['status']==1?'是':'否';
  $item['uid']= xxx;//这里如何替换成name?
  $newarr[] = $item;
}
</code>
Copy after login
Copy after login

回复内容:

有2个数组

<code>$array1 =[
[0]=>
  array(3) {
    ["id"]=> "1",
    ["uid"]=>'123',
    ["status"]=>'0'
[1]=>
  array(3) {
    ["id"]=> "2",
    ["uid"]=>'321',
    ["status"]=>'1'
]
$array2 =[
[0]=>
  array(2) {
    ["uid"]=> "123",
    ["name"]=>'张三'
[1]=>
  array(2) {
    ["uid"]=> "321",
    ["name"]=>'李四'
]
</code>
Copy after login
Copy after login

我在循环输出array1的时候。如何把uid替换成array2中的name?

<code>foreach($array1 as $item) {
  $item['status']= $item['status']==1?'是':'否';
  $item['uid']= xxx;//这里如何替换成name?
  $newarr[] = $item;
}
</code>
Copy after login
Copy after login

2个数组的匹配数据的位置是一一对应的么? 如果这样, 比较简单:

<code>$count = count($array1);
for ($i = 0; $i </code>
Copy after login

这样就可以了, 这种情况用foreach反而不方便.

假如数据不匹配, 需要在array2中搜索的话, 给个简单的例子:

<code>foreach ($array1 as &$item) {
    $item['uid'] = get_name($array2, $item['uid']);
}

function get_name(&$data, $uid)
{
    foreach ($data as &$item) {
        if ($item['uid'] == $uid) {
            $name = $item['name']
            unset($item);
            return $name;
        }
    }
}
</code>
Copy after login

再来拓展一下

<code>$array3 = function() use($array2) {
    $res = array();
    foreach ($array2 as $item) {
        $res[$item['uid']] = $item['name'];
    }
    return $res;
};

foreach ($array1 as &$item) {
    $item['uid'] = $array3[$item['uid']];
}
</code>
Copy after login

<code>$array2 = array_column($array2, 'name', 'uid');
foreach($array1 as &$arr) $arr['uid'] = $array2[$arr['uid']];
</code>
Copy after login

喷了,换个思路?
http://php.net/manual/en/function.array-merge-recursive.php

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template