Chords
Chords

Reputation: 6850

Switch multidimensional array key for value from within array

I have the following multidimensional array, returned from a query:

Array
(
    [0] => Array
        (
            [dimension] => string
            [value_1] => 100
            [value_2] => 200
        )

What I'm looking to do is create this format instead, so I can access data within it by writing something like $data['dimension']['key']:

Array
(
    [string] => Array
        (
            [dimension] => string
            [value_1] => 100
            [value_2] => 200
        )

Is there a clean way to do this, or should I start playing with loops?

Upvotes: 1

Views: 1383

Answers (3)

Stephen Kaufman
Stephen Kaufman

Reputation: 484

you could access the data within as it is now, without more array modification by using this:

$p = xml_parser_create();
xml_parse_into_struct($p, $simple, $vals, $index);
xml_parser_free($p);
//in case you want to view data in the arrays
//echo "Index array\n";
//print_r($index);
//echo "\nVals array\n";
//print_r($vals);

$answer = $vals[0][value_1];
echo $answer;

it should = 100

Upvotes: 0

revoke
revoke

Reputation: 559

You can create new array by combining keys and values:

array_combine(array_column($array, 'dimension'), $array)

But remember that the dimension have to be unique.

Upvotes: 1

ɴᴀᴛᴇ ᴅᴇᴠ
ɴᴀᴛᴇ ᴅᴇᴠ

Reputation: 4611

Only way I know how to do it would be with a loop.

$new = Array();
foreach($old as $key => $value) {
    $new[$value['dimension']] = $value;
}

print_r($new);

Upvotes: 1

Related Questions