gpt4 book ai didi

php - 将数组插入数组 - 关键问题

转载 作者:IT王子 更新时间:2023-10-29 00:05:44 27 4
gpt4 key购买 nike

我正在尝试将多个数组插入 1 个大数组,从而产生一个 2 级数组。

例如,我得到了这组数组:

Array(    [cod] => ddd    [denum] => ffffffffffffffff    [descr] => ggggggg    [cant] => 3)Array(    [cod] => fff    [denum] => dfgdfgdfgdfgdfg    [descr] => dfgdfgdfgdfgdfg    [cant] => 33)

But, after array push, i get this array:

Array(    [0] => Array        (            [0] => ddd            [1] => ffffffffffffffff            [2] => ggggggg            [3] => 3        )    [1] => Array        (            [0] => fff            [1] => dfgdfgdfgdfgdfg            [2] => dfgdfgdfgdfgdfg            [3] => 33        ))

Basically this is what i want to do, BUT, if you notice after the push, the keys are forgotten, and converted to numeric.

This is what i want it to look like:

Array(    [0] => Array        (            [cod] => ddd            [denum] => ffffffffffffffff            [descr] => ggggggg            [cant] => 3        )    [1] => Array        (            [cod] => fff            [denum] => dfgdfgdfgdfgdfg            [descr] => dfgdfgdfgdfgdfg            [cant] => 33        ))

sample code im using:

$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
array_push($res_arr_values, array_values($row));
}

有人可以帮我吗?

最佳答案

不要在你的 $row

上使用 array_values
$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
array_push($res_arr_values, $row);
}

另外,向数组添加值的首选方法是编写 $array[] = $value;,而不是使用 array_push

$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$res_arr_values[] = $row;
}

并且进一步的优化是不调用mysql_fetch_array($result, MYSQL_ASSOC),而是直接使用mysql_fetch_assoc($result)

$res_arr_values = array();
while ($row = mysql_fetch_assoc($result))
{
$res_arr_values[] = $row;
}

关于php - 将数组插入数组 - 关键问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9554799/

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