PHP:将数组整数索引更改为键字符串 [英] PHP: Change Array Integer Index to Key String

查看:387
本文介绍了PHP:将数组整数索引更改为键字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数组:

I have an array like so:

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

我想使用PHP更改数组结构,使其看起来像这样:

I would like to use PHP to change my array structure to look like this:

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

有人可以帮助我吗?到目前为止,我的代码是:

Can anybody help me out with this? Here is what I have for code so far:

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

此代码抛出未定义索引:-:description 我所有索引的错误。 -:description 会将每个错误更改为其所在的索引。

This code throws an Undefined index: - :description error for all of my indexes. The - :description changes in each error to the index that it is on however.

推荐答案

您非常接近,请尝试以下操作:

You were very close, try this:

$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() 。这是另一个示例:


The big problem came in your attempt to modify the current array. This will prove more difficult than it is worth, when you can just create a new array and set the key/value combos based on the exploded value from the initial array. Also, notice my shortcut with the use of list(). Here is another example:

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

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

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

这篇关于PHP:将数组整数索引更改为键字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆