gpt4 book ai didi

php - 如何用另一个结构格式化关联数组?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:47:29 27 4
gpt4 key购买 nike

我有这样的查询:

select truck, oil_type, km_min, km_max from trucks;

我正在使用 codeigniter 并使用 $query->result_array() 函数,因此它被加载到具有此结构的关联数组中:

/*

array(
truck
oil_type
km_min
km_max
)

*/

$arr[0]["truck"] = 2;
$arr[0]["oil_type"] = 2;
$arr[0]["km_min"] = 345;
$arr[0]["km_max"] = 567;
$arr[1]["truck"] = 2;
$arr[1]["oil_type"] = 4;
$arr[1]["km_min"] = 234;
$arr[1]["km_max"] = 867;
$arr[2]["truck"] = 1;
$arr[2]["oil_type"] = 2;
$arr[2]["km_min"] = 545;
$arr[2]["km_max"] = 867;
$arr[3]["truck"] = 4;
$arr[3]["oil_type"] = 3;
$arr[3]["km_min"] = 45;
$arr[3]["km_max"] = 567;

然后,我尝试重组它,按 id 对卡车进行分组,如下所示:

/*

trucks - array(
truck
truck_data - array(
oil_type
km_min
km_max
)
)

*/

$arr["truck"][0]= 2;
$arr["truck"][0]["truck_data"][0]["oil_type"] = 2;
$arr["truck"][0]["truck_data"][0]["km_min"] = 345;
$arr["truck"][0]["truck_data"][0]["km_max"] = 567;
$arr["truck"][0]["truck_data"][1]["oil_type"] = 4;
$arr["truck"][0]["truck_data"][1]["km_min"] = 234;
$arr["truck"][0]["truck_data"][1]["km_max"] = 867;
$arr["truck"][1]= 1;
$arr["truck"][1]["truck_data"][0]["oil_type"] = 2;
$arr["truck"][1]["truck_data"][0]["km_min"] = 545;
$arr["truck"][1]["truck_data"][0]["km_max"] = 867;
$arr["truck"][2]= 4;
$arr["truck"][2]["truck_data"][0]["oil_type"] = 3;
$arr["truck"][2]["truck_data"][0]["km_min"] = 45;
$arr["truck"][2]["truck_data"][0]["km_max"] = 567;

我想到了类似下面的代码:

$res = $query->result_array();
$cnt_total = count($res);
$y = 0;

for ($x=0; $x < $cnt_total -1 ; $x++) {

$truck = $res[$x]["truck"];
$trucks["truck"][$y] = $truck;

$q = $x + 1;
$i = 0;

do{
$trucks[$y][$i]["oil_type"] = $res[$q]["oil_type"];
$trucks[$y][$i]["km_min"] = $res[$q]["km_max"];
$trucks[$y][$i]["km_max"] = $res[$q]["km_max"];

$q++;
$i++;
if ($q <= $cnt_total) break;
} while ( $truck === $res["truck"][$q] );

$y++;

}

但不能正常工作……我离解决方案太远了?在这种特殊情况下,表现对我来说很重要。

有一个 phpfiddle,您可以在其中尝试:<强> http://phpfiddle.org/main/code/67j-ui5

任何想法、提示或建议将不胜感激,如果您需要更多信息,请告诉我,我将编辑帖子。

最佳答案

试试这个:

$res = $query->result_array();

$trucks = array();
foreach ($res as $row) {
$truck["truck"] = $row["truck"];
$truck["truck_data"] = array(
'oil_type' => $row["oil_type"],
'km_min' => $row["km_min"],
'km_max' => $row["km_max"],
);
$trucks[] = $truck;
}

var_dump($trucks);

关于php - 如何用另一个结构格式化关联数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19506945/

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