1

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?

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, FDL. Most of my code looks like this and I'm trying to make the jump to 'smarter' programming, so I figured I'd ask. I appreciate your response!
1

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.

1 Comment

Work perfect :)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.