gpt4 book ai didi

php - 如何压缩数组中的值?

转载 作者:行者123 更新时间:2023-12-02 07:17:44 25 4
gpt4 key购买 nike

我有一个元素数组,我需要更改数组开头的元素,我正在使用 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);
}
}
}

是否有更好、更简洁的方法来实现这一点?

最佳答案

我对您的代码段进行了一些修改以使其正常工作,

$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
)

)

关于php - 如何压缩数组中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56543956/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com