0

I have a json array like below. I need to get the index into a new array, how is this possible? Arrays are my weakness for some reason just cant grasp them. I can easily get id value, but cannot get the index (e.g 11111111). Any help would be appreciated.

Update please see the revised, my fault for not including the full multi dimensional array.

Below only outputs one result where I need all results.

<?php

$json = '[{
    "11111111": {
        "id": "val_somevalue5555",
        "customer": {
            "32312": {
                "name": "jane doe"
            }
        }
    },
    "2222222": {
        "id": "val_somevalue25",
        "customer": {
            "32312234": {
                "name": "jane doe"
            }
        }
    }
}]';

$jsonarr = json_decode($json, true);

$newarr = [];

foreach($jsonarr as $value)
{
    $key = key($value);
    $newarr[] = ['key' => $key, 'id' => $value[$key]['id']];
}
var_dump($newarr);

    expected looped output 
    key 11111111 
    id val_somevalue5555
    ... looped.
1
  • I have updated my answer try the new solution Commented Dec 20, 2017 at 21:00

6 Answers 6

1

you can use array_keys() or key() with a foreach loop for this(DEMO):

$newarr = [];

foreach($jsonarr as $value)
{
    //$key = array_keys($value)[0];
    $key = key($value);
    $newarr[] = ['key' => $key, 'id' => $value[$key]['id']];
}
var_dump($newarr);

Output:

array(2) {
  [0]=>
  array(2) {
    ["key"]=>
    int(11111111)
    ["id"]=>
    string(17) "val_somevalue5555"
  }
  [1]=>
  array(2) {
    ["key"]=>
    int(2222222)
    ["id"]=>
    string(15) "val_somevalue25"
  }
}

Edit: With the updated json, you can use the following way, using 2 foreach loops (DEMO):

$newarr = [];

foreach($jsonarr as $json)
{
    foreach($json as $key => $value)
    {
        $newarr[] = ['key' => $key, 'id' => $value['id']];
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is good, but see my updated description. I am only getting one result with this.
But if you look at my output you’ll see that it ouputs both results
0

PHP supports a slightly different foreach syntax that extracts both the array key and the array value:

foreach ( $jsonarr as $key => $value ) {
    $newarr[] = ['key' => $key, 'id' => $value];
}

Use this if you need the key ("11111111" and "2222222" in your example).

Comments

0
<?php
$json = '[{
    "11111111": {
        "id": "val_somevalue5555"
    }
},
{
    "2222222": {
        "id": "val_somevalue25"
    }
}
]';

$jsonarr = json_decode($json, true);

$newarr = [];
foreach($jsonarr as $key => $value) {
        $newarr[] = ['key' => key($value), 'id' => current($value)['id']];
}

foreach($newarr as $key) {
    echo 'key '.$key['key'] . PHP_EOL;
    echo 'id '.$key['id'] . PHP_EOL;
}

Comments

0

If you remove what looks like embedded components in the $json string (otherwise it won't parse) then var_export the output of json_decode() you'll get this:

array (
   0 => array (
      11111111 => array (
          'id' => 'val_somevalue5555',
      ),
   ),
   1 => array (
      2222222 => array (
          'id' => 'val_somevalue25',
      ),
   ),
)

You have a double-nested array, hence...

foreach ($jsonarr as $obj) {
   foreach ($obj as $name=>$value) {
      print "$name = $value[id]\n";
      break;
   }
}

or you can reference the elements directly:

print $jsonarr[0]['11111111']['id'];

Comments

0

You can create an array of the keys of an existing array using the array_keys() function

http://php.net/manual/en/function.array-keys.php

If you don't want the keys in a separate array, and instead just want to access them directly, when you are doing a 'foreach' loop of an array, you can choose to assign a variable to the current key by doing

foreach($jsonarr as $key => $value){...}  

Because your original array is actually multidimensional (each $key has a $value that is also stored as an array of "id": "value") - this means taking one more step to get the value of key 'id':

foreach($jsonarr as $key => $value){     
 $newarray[] = ['key' => $key, 'id' => $value['id'];
}

Comments

0

First, you are not accessing the deep enough before iterating.

If you call var_export($jsonarr); you will see:

array (                                 // an indexed array of subarrays
  0 =>
  array (                               // an associative array of subarrays, access via [0] syntax (or a foreach loop that only iterates once)
    11111111 =>                         // this is the subarray's key that you want
    array (
      'id' => 'val_somevalue5555',      // this is the value you seek from the id element of 1111111's subarray
      'customer' => 
      array (
        32312 => 
        array (
          'name' => 'jane doe',
        ),
      ),
    ),
    2222222 =>                         // this is the subarray's key that you want
    array (
      'id' => 'val_somevalue25',      // this is the value you seek from the id element of 2222222's subarray
      'customer' => 
      array (
        32312234 => 
        array (
          'name' => 'jane doe',
        ),
      ),
    ),
  ),
)

Code: (Demo)

$jsonarr = json_decode($json, true);
$result=[];
//                     vvvv-avoid a function call (key()) on each iteration by declaring here
foreach($jsonarr[0] as $key=>$subarray){
    //          ^^^-drill down into the first level (use another foreach loop if there may be more than one)
    $result[]=['key'=>$key,'id'=>$subarray['id']];
}
var_export($result);

Output:

array (
  0 => 
  array (
    'key' => 11111111,
    'id' => 'val_somevalue5555',
  ),
  1 => 
  array (
    'key' => 2222222,
    'id' => 'val_somevalue25',
  ),
)

p.s. If $jsonarr has more than one element in its first level, you should use a foreach() loop like this:

foreach($jsonarr as $array1){
    foreach($array1 as $key=>$array2){
        $result[]=['key'=>$key,'id'=>$array2['id']];
    }
}

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.