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


PHP: Change Array Integer Index to Key String

我有一个像这样的数组:

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在每个错误中都更改为它所在的索引。

你很接近了,试试这个:

$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];
$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;