Cassie Liu
Cassie Liu

Reputation: 195

How to get the index of an associative array in PHP?

The following JSON string shows the correctness of two questions submitted and I want to know the IDs of the two questions, namely the indices of the associatve arrays within "submission", "question1" and "question2". How am I supposed to do that? Thanks!

<?php
$test = 
'{
    "event_source": "server",
    "event_type": "problem_check",
    "submission": {
        "question1":{
            "correct":false
        }
        "question2":{
            "correct":true
        }
    }
}';

$jarray = json_decode($test, true);

Upvotes: 2

Views: 64

Answers (3)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72289

1.You json data have some missing , and "" (check my output links for correct format)

2.Use foreach() if you want to show each question submission result.

$jarray = json_decode($test, true);

foreach($jarray['submission'] as $key=>$value){
    echo $key. ' answer is '.$value['correct'].PHP_EOL;
}

Output:- https://3v4l.org/T3sh4 OR https://3v4l.org/3lUNF

3.If you want only keys then do:-

$questionIds = array_keys($jarray['submission']); 

Output:- https://3v4l.org/f0oHq

References:-

json_decode()

foreach()

array_keys()

Upvotes: 3

PHP Geek
PHP Geek

Reputation: 4033

you can use array_keys()

$newArray = array_keys($test);

Upvotes: 1

Aaron
Aaron

Reputation: 1727

A rather simple approach but it should do the trick:

$i = 0;
foreach($jarray['submission'] as $key => $val) {
  echo $key " is the index ". $i;
  $i++;
}

Upvotes: 2

Related Questions