如何更改阵列自动键?

时间:2014-12-29 19:06:24

标签: php arrays

$arr = Array ( [0] => aaa [1] => bbb [2] => ccc )

这个数组,如何更改为这两个数组?

A

array("name"=>"aaa","name"=>"bbb","name"=>"ccc");

Array
(
    [0] => Array
        (
            [id] => 0
            [name] => aaa
        )
    [1] => Array
        (
            [id] => 1
            [name] => bbb
        )
    [2] => Array
        (
            [id] => 2
            [name] => ccc
        )

)

2 个答案:

答案 0 :(得分:1)

这应该适合你:

(1.在第一个数组中,索引从0开始自动设置.2。关联数组中必须有唯一的键)

<?php

    $arr1 = array("aaa", "bbb", "ccc");
    $arr2 = array("name1" => "aaa", "name2" => "bbb", "name3" => "ccc");
    $result = array();

    foreach($arr2 as $k => $v) {
        $key = array_search($k, array_keys($arr2));
        $result[$key]["id"] = array_search($v, $arr1);
        $result[$key]["name"] = $v;
    }

    print_r($result);

?>

输出:

Array
(
    [0] => Array
        (
            [id] => 0
            [name] => aaa
        )

    [1] => Array
        (
            [id] => 1
            [name] => bbb
        )

    [2] => Array
        (
            [id] => 2
            [name] => ccc
        )

)

答案 1 :(得分:0)

嗯,半个答案 - 必须阅读说明......

无法创建具有相同“name”键的数组,因为您的数组中包含一行。

$arr = Array ( 0 => 'aaa',  1 => 'bbb',  2 => 'ccc' );

$outList = array();
foreach ($arr as $key => $value) {
    $outList[$key]= array('id' => $key, 'name' => $value);
}


echo '<pre>Before: <br />';
print_r($arr);
echo '</pre>';
echo '<pre>After: <br />';
print_r($outList);
echo '</pre>';


Before: 
Array
(
    [0] => aaa
    [1] => bbb
    [2] => ccc
)

After: 
Array
(
    [0] => Array
        (
            [id] => 0
            [name] => aaa
        )

    [1] => Array
        (
            [id] => 1
            [name] => bbb
        )

    [2] => Array
        (
            [id] => 2
            [name] => ccc
        )

)