我有一个元素数组,我需要在数组的开头更改元素,而我正在使用foreach。
Array
(
[0] => Array
(
[0] => user
[1] => address
[2] => detail
[3] => name
[4] => family
)
[1] => Array
(
[0] => user
[1] => address
)
[2] => Array
(
[0] => user
[1] => address
[2] => detail
[3] => name
)
)
我想要这个输出:
Array
(
[0] => Array
(
[0] => user.address.detail.name
[1] => family
)
[1] => Array
(
[0] => user
[1] => address
)
[2] => Array
(
[0] => user.address.detail
[1] => name
)
)
这是我的代码,但似乎不起作用。
$firstTemp = "";
foreach ($temps as $row => $temp) {
if (count($temp) > 2) {
foreach ($temp as $k => $content) {
$firstTemp .= $content . '.';
$endTemp = end($temp);
}
}
}
有没有更好,更简洁的方法来实现这一目标?
答案 0 :(得分:5)
您可以pull the last element
和implode()
来自数组Like的其余元素:
$formatted = [];
foreach($temps as $arr) {
if(count($arr) == 0){
return;
}
$last = array_pop($arr);
if(count($arr) > 0) //check if array not empty.
$formatted[] = [implode(".", $arr), $last];
else
$formatted[] = [$last];
}
答案 1 :(得分:4)
我对您的代码段进行了一些修改以使其正常工作,
$result = [];
foreach ($temps as $row => $temp) {
if (count($temp) > 2) {
// I am taking a slice of the array except for last element and imploding it with `.`
// then I am fetching the last element of an array
// creating an array and pushing it into the result variable
$result[] = [implode(".", array_slice($temp, 0, count($temp) - 1)), end($temp)];
}else{
$result[] = $temp;
}
}
我正在使用array_slice内除最后一个元素之外的所有元素。
end
我曾经获取过数组的最后一个元素。
Demo。
编辑1
实现相同目标的另一种方法,
$result = [];
foreach ($temps as $row => $temp) {
if (count($temp) > 2) {
// except last elements
$result[] = [implode(".", array_slice($temp, 0, -1)), end($temp)];
}else{
$result[] = $temp;
}
}
Demo。
编辑2
$result = [];
foreach ($temps as $row => $temp) {
$result[] = (count($temp) > 2 ? [implode(".", array_slice($temp, 0, -1)), end($temp)] : $temp);
}
Demo。
编辑3
$result = array_map(function($temp){
return (count($temp) > 2 ? [implode(".", array_slice($temp, 0, -1)), end($temp)] : $temp);
},$temps);
Demo。
编辑4 :无条件
$result = array_map(function($temp){
return [implode(".",array_slice($temp,0,-1)),array_pop($temp)];
},$temps);
编辑5
$result = array_map(function($temp){
return [implode(".",array_slice($temp,0,-1)),end($temp)];
},$temps);
Demo。
输出:
Array
(
[0] => Array
(
[0] => user.address.detail.name
[1] => family
)
[1] => Array
(
[0] => user
[1] => address
)
[2] => Array
(
[0] => user.address.detail
[1] => name
)
)
答案 2 :(得分:0)
$data = [
[
'user',
'address',
'detail',
'name',
'family',
], [
'user',
'address',
], [
'user',
'address',
'detail',
'name',
'family',
]
];
$result = array_map(function($item) {
$last = array_pop($item);
return [implode('.', $item), $last];
}, $data);
答案 3 :(得分:0)
您可以在不使用两个foreach
结构的情况下进行操作。例如:
$result = array_map(function (&$temp) {
$last = array_pop($temp);
$first = implode('.', $temp);
return [$first, $last];
}, $temps);