gpt4 book ai didi

php - 如何将三维数组更改为一维数组(PHP)

转载 作者:行者123 更新时间:2023-12-04 06:10:51 26 4
gpt4 key购买 nike

我有一个三维数组。我想修正一个函数以将其转换为一维数组并保留前一个子键。我怎么做?

array(2) {
[0]=>
array(2) {
[0]=>
array(2) {
["id"]=>
string(1) "4"
["assignedlessons"]=>
string(2) "69"
}
[1]=>
array(2) {
["id"]=>
string(1) "4"
["assignedlessons"]=>
string(3) "308"
}
}
array(2) {
[0]=>
array(2) {
["id"]=>
string(1) "10"
["assignedlessons"]=>
string(2) "50"
}
[1]=>
array(2) {
["id"]=>
string(1) "10"
["assignedlessons"]=>
string(2) "91"
}
}
}

我想把它转换成这样的结构:
   array(0) {
["id"]=>
string(1) "4"
["assignedlessons"]=>
string(2) "69"
}

array(1) {
["id"]=>
string(1) "4"
["assignedlessons"]=>
string(3) "308"
}

array(2) {
["id"]=>
string(1) "10"
["assignedlessons"]=>
string(2) "50"
}
array(3) {
["id"]=>
string(1) "10"
["assignedlessons"]=>
string(2) "91"
}

我所拥有的是这个功能:
function toSingleDimentionalArray($array){
$final = array();
foreach($array as $value){
foreach($array as $key => $val){
$final[]['id'] = $val['id'];
$final[]['assignedlessons'] = $val['assignedlessons'];
}

}
return $final;
}

但它只返回这样的东西:
array(19648) {
[0]=>
array(1) {
["id"]=>
string(1) "4"
}
[1]=>
array(1) {
["assignedlessons"]=>
string(2) "69"
}
[2]=>
array(1) {
["id"]=>
string(1) "4"
}
[3]=>
array(1) {
["assignedlessons"]=>
string(3) "308"
}

最佳答案

这将工作

function toNotActuallyASingleDimensionalArray($array) {
$final = array();
foreach($array as $subarray) {
foreach($subarray as $val) {
$final[] = $val;
}
}
return $final;
}

关于php - 如何将三维数组更改为一维数组(PHP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7797549/

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