0

I need do extract all cpu ids from this kind of JSON response:

$response = json_decode('{
  "code": 26,
  "result": {
    "0": {
      "cpu": {
        "423": {
          "prod": "Intel",
          "model": "i5-8300H",
        },
        "424": {
          "prod": "Intel",
          "model": "i7-8750H",
        }
      }
    }
  }
}');

I managed to obtain first id 423 with this code:

$response = $response->result;
foreach ($response as $item) {
            $key = key((array)$item->cpu);
        }

but I can't find the way to get the reset, in this case 424. How can I do it?

4
  • 1
    Your $response assignment is not valid PHP syntax. Commented Aug 7, 2019 at 23:44
  • Did you mean to write $response = json_decode('{...}'); Commented Aug 7, 2019 at 23:46
  • Use array_keys() instead of key(); Commented Aug 7, 2019 at 23:47
  • fixed the syntax Commented Aug 7, 2019 at 23:49

2 Answers 2

2

Since you didn't use the true second argument to json_decode(), all the elements are being parsed as objects, not arrays. Use json_decode(..., true) to get arrays.

Then you can use array_keys() to get all the keys of the cpu array.

$response = json_decode('
{
  "code": 26,
  "result": {
    "0": {
      "cpu": {
        "423": {
          "prod": "Intel",
          "model": "i5-8300H"
        },
        "424": {
          "prod": "Intel",
          "model": "i7-8750H"
        }
      }
    }
  }
}', true);
$response = $response['result'];
foreach ($response as $item) {
    $keys = array_keys($item['cpu']);
    var_dump($keys);
}
Sign up to request clarification or add additional context in comments.

Comments

0

You just need to iterate over the cpu values as well; you can extract the key directly in the foreach:

$results = $response->result;
foreach ($results as $item) {
    foreach ($item->cpu as $key => $cpu) {
        echo "$key\n";
    }
}

Output:

423
424

Demo on 3v4l.org

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.