Array_map和array_combine用于两个以上的数组

时间:2019-01-05 06:31:04

标签: php arrays

众所周知,array_combine仅用于两个数组。例如

$name = array('John','Brian','Raj');
$salary = array('500','1000','2000');
$details = array_combine($name, $salary);
foreach($details AS $name => $salary){ echo $name."'s salary is ".$salary."<br/>";
}

在此列表中添加2个数组

$dpart = array('HTML','CSS','PHP');
$address = array('Floor 3','Floor 5','Floor 6');

在那种情况下,仅array_combine是不够的,因此我发现array_map是更好的解决方案。但是如何回显array_map结果呢?如何访问array_map生成的数组的值并根据个人要求进行获取。

$details = array_map(function($item) {
    return array_combine(['name', 'salary', 'dpart', 'address'], $item);
}, array_map(null, $name, $salary, $dpart, $address));

现在的要求是使用单独的值访问所有四个数组。例如

$name."'s salary is ".$salary.", address is ".$address.", depart is ".$dpart

2 个答案:

答案 0 :(得分:1)

不将它们组合在一起可能很简单:

<?php
$name    = array('John','Brian','Raj');
$salary  = array('500','1000','2000');
$dpart   = array('HTML','CSS','PHP');
$address = array('Floor 3','Floor 5','Floor 6');

foreach($name as $k => $v)
    printf(
        "%s's salary is %d, address is %s, depart is %s\n",
        $name[$k],
        $salary[$k],
        $dpart[$k],
        $address[$k]
    );

输出:

John's salary is 500, address is HTML, depart is Floor 3
Brian's salary is 1000, address is CSS, depart is Floor 5
Raj's salary is 2000, address is PHP, depart is Floor 6

您可以遍历array_map,并使用列表或项目索引:

foreach(array_map(null, $name, $salary, $dpart, $address) as $item) {
    list($n, $s, $d, $a) = $item;
    print "$n's salary is $s, address is $d, depart is $a\n";
}

答案 1 :(得分:1)

您只需使用foreach即可访问结果。将$details循环为

foreach($details as $item) {
    $name    = $item['name'];
    $salary  = $item['salary'];
    $dpart   = $item['dpart'];
    $address = $item['address'];
    echo $name."'s salary is ".$salary.", address is ".$address.", depart is ".$dpart."<br/>";
}

或者在循环内没有分配:

foreach($details as $item)
    print "{$item['name']}'s salary is {$item['name']}, address is {$item['dpart']}, depart is {$item['address']}<br/>";