1

So I have this array that saves a json string.

Array
(
    [0] => "2jDQoU9D2wu04wqkg0ImUI":{"date":"2016-08-02 14:08:49","type":"story","story_id":"2jDQoU9D2wu04wqkg0ImUI","series_id":"1RAv0uDbcIieYgYqywqYmk"}
)

I want to be able to access just the value "2jDQoU9D2wu04wqkg0ImUI" at the start of the json string and then also be able to do something like $value[0]['type'] to get the type from this json string object. I'm pretty new to PHP and struggling to get this working. I've tried JSON encoding/decoding and can't seem to get anything to work.

What's the proper way to go about this? Thanks in advance.

3 Answers 3

1

I hope this code will solve your problem.

$array[0] = '"2jDQoU9D2wu04wqkg0ImUI":{"date":"2016-08-02 14:08:49","type":"story","story_id":"2jDQoU9D2wu04wqkg0ImUI","series_id":"1RAv0uDbcIieYgYqywqYmk"}';

//print_r($arr);

$JsonString = '{' . $array[0] . '}';

$json = json_decode($JsonString);

foreach($json as $key => $value){
   echo "Key : $key <br />";
   echo "Type : ". $value->type."<br />";
   echo "date : ". $value->date."<br />";
   echo "story_id : ". $value->story_id."<br />";
   echo "series_id : ". $value->series_id."<br />";
}
Sign up to request clarification or add additional context in comments.

1 Comment

Oh man thanks for this. No wonder nothing was working if the JSON was formatted incorrectly. Cheers.
0

so you have array $jsonArray and you want to access just the key of it

if its single dimension array :

  echo key($jsonArray); //prints 2jDQoU9D2wu04wqkg0ImUI

Otherwise if its multidimensional you can loop through it and do whatever you want with each key

foreach($jsonArray as $key => $value) {
    echo $key; //prints 2jDQoU9D2wu04wqkg0ImUI
}

Comments

0

Try this:

$arrayOfObjects = [];    
 foreach($array as $key => $value)  arrayOfObjects[] = json_decode($value);

Now you can loop through this new $arrayOfObjects

foreach($arrayOfObjects as $key => $object){
    echo $object->date . '<br>';
    echo $object->type . '<br>';
    echo $object->story_id . '<br>';
    echo $object->series_id . '<br> ==== >br> ';
}

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.