如何组合子数组的每个子数组并将它们存储为逗号分隔的字符串?
How to combine each subarray of subarrays and store them as comma separated strings?
我需要将所有子数组 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)
这可以通过一个循环和每个子数组中柱状值的内爆来简洁地解决。
代码 (Demo)
$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',
),
),
)
我需要将所有子数组 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)
这可以通过一个循环和每个子数组中柱状值的内爆来简洁地解决。
代码 (Demo)
$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',
),
),
)