我想更改多维数组的键

时间:2019-06-27 07:34:50

标签: php

我想更改多维数组的键。该数组包含键,如1,15,23,45,应将其替换为普通索引键,如0、1、2、3。我尝试了下面的代码。以下代码缺少某些内容。请任何人向我建议。

$keys = array_keys($data);
$d = 0;
foreach($data as $row){
    $key_data[$d] = $data[$keys[$d]];
    unset($row[$keys[$d]]);
    $d++;
}

当前输出

数组 (

[15] => Array
    (
        [0] => Array
            (
                [app_dealer_id] => 15
                [dealer_name] => Sharad Thombre
                [shopname] => Shivshankar Fertilizer
                [contact_num] => 9049121143
                [district] => Parbhani
            )

    )

[18] => Array
    (
        [0] => Array
            (
                [app_dealer_id] => 18
                [dealer_name] => Gajanan Khapre
                [shopname] => Shreyas Krishi Kendra
                [contact_num] => 8007791946
                [district] => Parbhani
            )

    )

)

预期输出:

Array
    (

        [0] => Array
            (
                [0] => Array
                    (
                        [app_dealer_id] => 15
                        [dealer_name] => Sharad Thombre
                        [shopname] => Shivshankar Fertilizer
                        [contact_num] => 9049121143
                        [district] => Parbhani
                    )

            )

        [1] => Array
            (
                [0] => Array
                    (
                        [app_dealer_id] => 18
                        [dealer_name] => Gajanan Khapre
                        [shopname] => Shreyas Krishi Kendra
                        [contact_num] => 8007791946
                        [district] => Parbhani
                    )

            )
)

2 个答案:

答案 0 :(得分:3)

使用array_values()

$array = array_values($array);

输出:-{https://3v4l.org/cUAdl

答案 1 :(得分:0)

来自php.net: array_values()返回数组中的所有值,并对数组进行数字索引。

因此,只需在循环后添加它即可重新索引数组:

$keys = array_keys($data);
$d = 0;
foreach($data as $row){
    $key_data[$d] = $data[$keys[$d]];
    unset($row[$keys[$d]]);
    $d++;
}
$newArray = array_keys($key_data);