4

I have an array like(result of json_decode):

array(2) {
  [0]=>
  object(stdClass)#1 (3) {
    ["key"]=>
    string(6) "sample"
    ["startYear"]=>
    string(4) "2000"
    ["endYear"]=>
    string(4) "2015"
  }
  [1]=>
  object(stdClass)#2 (3) {
    ["key"]=>
    string(13) "second_sample"
    ["startYear"]=>
    string(4) "1986"
    ["endYear"]=>
    string(4) "1991"
  }
}

I want to convert it to array like:

 array(2) {
  ["sample"]=>
  array(2) {
    ["startYear"]=>
    string(4) "2000"
    ["endYear"]=>
    string(4) "2015"
  }
  ["second_sample"]=>
  array(2) {
    ["startYear"]=>
    string(4) "1986"
    ["endYear"]=>
    string(4) "1991"
  }
}

Is there beauty way to do this (cureently I'm using foreach, but I'm not sure it is a best solution).

Added a code example:

<?php
$str='[{"key":"sample","startYear":"2000","endYear":"2015"},{"key":"second_sample","startYear":"1986","endYear":"1991"}]';

$arr=json_decode($str);

var_dump($arr);

$newArr=array();

foreach ($arr as $value){
$value=(array)$value;
$newArr[array_shift($value)]=$value;

}

var_dump($newArr);
1
  • 1
    Using foreach sounds like a pretty sane approach to this. Commented Nov 18, 2015 at 13:47

4 Answers 4

6

You can use array_reduce

$myArray = array_reduce($initialArray, function ($result, $item) {
    $item = (array) $item;

    $key = $item['key'];
    unset($item['key']);

    $result[$key] = $item;

    return $result;
}, array());
Sign up to request clarification or add additional context in comments.

2 Comments

I'd explicitly get the key key instead of relying on the order with array_shift; JSON dictionaries have no intrinsic order.
You're right @deceze .. I will update my answer.. Thanks
1

You can create the desired output without making any iterated function calls by using a technique called "array destructuring" (which is a functionless version of list()). Demo

Language Construct Style:

$result = [];
foreach ($array as $object) {
    [
        'key' => $key,
        'startYear' => $result[$key]['startYear'],
        'endYear' => $result[$key]['endYear']
    ] = (array)$object;
}
var_export($result);

Functional Style:

var_export(
    array_reduce(
        $array,
        function($result, $object) {
            [
                'key' => $key,
                'startYear' => $result[$key]['startYear'],
                'endYear' => $result[$key]['endYear']
            ] = (array)$object;
            return $result;
        },
        []
    )
);

Both will output:

array (
  'sample' => 
  array (
    'startYear' => '2000',
    'endYear' => '2015',
  ),
  'second_sample' => 
  array (
    'startYear' => '1985',
    'endYear' => '1991',
  ),
)

Comments

0

Simply you can use array_map like as

$result = array_map('get_object_vars',$your_array);

Edited:

As after checking your code that you've added an example over here there's no need to use an extra functions or loop to convert your array of objects into associative array instead you simply need to pass second parameter true within json_decode function like as

$arr = json_decode($json,true);

Demo

5 Comments

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - From Review
@RajeshJadav How does this not provide an answer?
I think this answer should be comment
First of all you're an android developer and user has requested for the answer that doesn't required foreach and did you tried this answer even once. @RajeshJadav
The answer provably does not provide the correct result.
0

An alternative to array_reduce and other provided solutions could be:

$list = array_combine(
  array_column($list, 'key'),
  array_map(fn ($item) => (array) $item, array_values($list))
);

Or:

$list = array_combine(
  array_column($list, 'key'),
  array_map('get_object_vars', $list)
);

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.