PHP:将数组整数索引更改为键字符串

时间:2014-08-22 19:42:00

标签: php arrays

我有一个像这样的数组:

Array (
    [0] => - :description: Rate the Code
    [1] => :long-description: ""
    [2] => :points: !float 5
)

我想使用PHP将我的数组结构更改为:

Array (
    [- :description] => Rate the Code
    [:long-description] => ""
    [:points] => !float 5
)

有人可以帮我解决这个问题吗?这是我到目前为止的代码:

for ($j = 0; $j < sizeof($array[$i]); $j++) {
    $pieces = explode(": ", $array[$i][$j]);

    $key = $pieces[0];
    $value = $pieces[1];

    $array[$i][$j] = $array[$i][$key];
}

此代码会为我的所有索引抛出Undefined index: - :description错误。但是,- :description会将每个错误更改为它所在的索引。

2 个答案:

答案 0 :(得分:3)

你非常接近,试试这个:

$initial = array(
    '- :description: Rate the Code',
    ':long-description: ""',
    ':points: !float 5'
);

$final = array();
foreach($initial as $value) {
    list($key, $value) = explode(": ", $value);
    $final[$key] = $value;
}

print_r($final);
// Array
// (
//     [- :description] => Rate the Code
//     [:long-description] => ""
//     [:points] => !float 5
// )

您尝试修改当前阵列时出现了一个大问题。当你可以创建一个新数组并根据初始数组中的爆炸值设置键/值组合时,这将证明比它值得更难。另外,请使用list()注意我的快捷方式。这是另一个例子:

$array = array('foo', 'bar');

// this
list($foo, $bar) = $array;

// is the same as 
$foo = $array[0];
$bar = $array[1];

答案 1 :(得分:0)

$array = [
    [
        '- :description: Rate the Code',
        ':long-description: ""',
        ':points: !float 5'
    ],

    [
        '- :description: Rate the Code',
        ':long-description: ""',
        ':points: !float 5'
    ],


    [
        '- :description: Rate the Code',
        ':long-description: ""',
        ':points: !float 5'
    ]
];

foreach($array as $key => $values) :
    $tmp = [];

    foreach($values as $k => $value) :
        $value = explode(': ', $value);
        $k = $value[0];
        unset($value[0]);
        $tmp[$value[0]] = implode(': ', $value);
    endforeach;

    $array[$key] = $tmp;
endforeach;