我需要在单个子数组中加入所有子数组Name
值。
给定输入格式:
Array
(
[0] => Array
(
[0] => Array
(
[Name] => kumar
)
[1] => Array
(
[Name] => siva
)
)
[1] => Array
(
[0] => Array
(
[Name] => Arun
)
[1] => Array
(
[Name] => Prem
)
)
)
要求的输出格式
Array
(
[0] => Array
(
[0] => Array
(
[Name] => kumar, siva
)
)
[1] => Array
(
[0] => Array
(
[Name] => Arun, Prem
)
)
)
我的编码尝试:
$final = array();
foreach ($NameArray as $row) {
foreach ($row as $rows) {
$final[] = $rows['Name'];
}
}
print_r($final);
分别显示。我需要每个子数组是一个单一的数组名称与逗号格式。
你可以这样做:
foreach($a as $k1=>$ar1){
$text = '';
foreach($ar1 as $t){
$text .= "{$t['Name']}, ";
}
unset($a[$k1]);
$a[$k1][0]['Name'] = substr($text,0,-2);
}
var_dump($a);
输出:array (size=2)
0 =>
array (size=1)
0 =>
array (size=1)
'Name' => string 'kumar, siva' (length=10)
1 =>
array (size=1)
0 =>
array (size=1)
'Name' => string 'Arun, Prem' (length=9)
这可以通过一个循环和每个子数组中列值的内爆来简洁地解决。
代码(演示)
$a = [
[['Name' => 'kumar'],['Name' => 'siva']],
[['Name' => 'Arun'],['Name' => 'Prem']]
];
foreach ($a as $i => $group) {
$result[$i][] = ['Name' => implode(', ', array_column($group, 'Name'))];
}
var_export($result);
输出:array (
0 =>
array (
0 =>
array (
'Name' => 'kumar, siva',
),
),
1 =>
array (
0 =>
array (
'Name' => 'Arun, Prem',
),
),
)