如何将嵌套数组键转换为索引php

时间:2018-12-19 12:10:32

标签: php tableau

我有这个数组:

`$arr = array(
    'foo' => 'foo',
    'bar' => array(
        'baz' => 'baz',
        'candy' => 'candy',
        'vegetable' => array(
            'carrot' => 'carrot',
        ),
    ),
);

,我想将其更改为此:

$arr = array(
'0' => 'foo',
'1' => array(
    '0' => 'baz',
    '1' => 'candy',
    '2' => array(
        '0' => 'carrot',
    )
),
);

我尝试过array_values函数,但它仅更改第一级,如下所示:

$arr = array(
'0' => 'foo',
'1' => array(
    'baz' => 'baz',
    'candy' => 'candy',
    'vegetable' => array(
        'carrot' => 'carrot',
    )
),
);

3 个答案:

答案 0 :(得分:1)

Dipti代码很棒。我做了一点点修饰:

function array_values_recursive(array $arr ) : array {
    $result = array();
    foreach ($arr as $value) {
        $result[] = is_array($value) ? array_values_recursive($value) : $value;
    }
    return $result;
}

答案 1 :(得分:0)

请使用以下功能。您必须迭代循环递归/嵌套循环

function array_values_recursive($arr)
{
    $arr2=[];
    foreach ($arr as $key => $value)
    {
        if(is_array($value))
        {            
            $arr2[] = array_values_recursive($value);
        }else{
            $arr2[] =  $value;
        }
    }

    return $arr2;
}
print_r(array_values_recursive($arr))

这应该有效。谢谢

答案 2 :(得分:0)

这是我的真实代码:

$arr = array(); 
while($d = mysqli_fetch_assoc($result)) {
 $sub_data["id"] = $d["id"];
 $sub_data["date"] = $d["date"]; 
 $sub_data["n_trans"] = $d["n_trans"]; 
 $sub_data["doc"] = $d["doc"];     

    if(!isset($arr[$d['date']])) {
        $arr[$d['date']] = array();
    }

    if(!isset($arr[$d['date']][$d['n_trans']])) {
        $arr[$d['date']][$d['n_trans']] = array();
    }

    array_push($arr[$d['date']][$d['n_trans']], $d['doc']);

}
       echo '<pre>';
       print_r(array_values($arr));  
       echo '</pre>';  
?>

这是查询的结果,我尝试更改第二级([32weds] => Array)删除文本并放入一个整数(([0] => Array):

 Array(
    [0] => Array(
            [text] => 2018-11-01
            [nodes] => Array(
                    [32weds] => Array(
                            [text] => 32weds
                            [nodes] => Array
                                (
                                    [0] => 32.png
                                    [1] => 32 (1).png
                                )

                        )

                    [qwerty] => Array
                        (
                            [text] => qwerty
                            [nodes] => Array
                                (
                                    [0] => 5384a97ee9d6b (2).pd
                                )

                        )

                )

        )
    )

无需更改数组格式。