Nicolas
Nicolas

Reputation: 1143

PHP: Change Array Integer Index to Key String

I have an array like so:

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

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

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.

Upvotes: 2

Views: 2708

Answers (2)

num8er
num8er

Reputation: 19372

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

Upvotes: 0

Sam
Sam

Reputation: 20486

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
// )

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

Upvotes: 4

Related Questions