Extract each level data with php - php

The following is the JSon data.
{
"statusType": "OK",
"entity": [
{
"category": "category1","difficultyLevel": "Easy",
"quizAnswerChoices": [{"choiceText": "Yes", "choiceTextHash": "c3f1130841b507a4d1e0f45971d990c6ecd25406"}, {"choiceText": "Yes", "choiceTextHash": "c3f1130841b507a4d1e0f45971d990c6ecd25406"}]
}
],
"entityType": "java.util.ArrayList",
"status": 200,
"metadata": {}
}
I need to parse
- entity
- quizAnswerChoices (count the item)
How to retrieve each choiceText etc

Use
$json='{
"statusType": "OK",
"entity": [
{
"category": "category1","difficultyLevel": "Easy",
"quizAnswerChoices": [{"choiceText": "Yes", "choiceTextHash": "c3f1130841b507a4d1e0f45971d990c6ecd25406"}, {"choiceText": "Yes", "choiceTextHash": "c3f1130841b507a4d1e0f45971d990c6ecd25406"}]
}
],
"entityType": "java.util.ArrayList",
"status": 200,
"metadata": {}
}';
$encodedJson= json_decode($json,true);
$quizAnswerChoices=$encodedJson['entity'][0]['quizAnswerChoices'];
echo 'Count: '.count($quizAnswerChoices);

Use this
$arry = json_decode($json,true);
foreach ($arry['entity'] as $ke => $ve) {
foreach ($ve['quizAnswerChoices'] as $k => $v) {
print_r($v);
}
}

Lets consider you are recieving this json in a variable called "$contents".
All you have to do is decode it:
$decoded = json_decode($contents, true); //True so, the decoded object will be converted into an ssociative array
print_r($decoded);

If you do a json_decode like
$data = json_decode(json_data);
Then $data will be a traversable array
$data['entity']['quizAnswerChoices'] etc

Use json_decode to convert json to array
$dataArray = json_decode($json_string, true)
$dataArray['entity']; // entity
$dataArray['entity']['quizAnswerChoices']; // quizAnswerChoices
$dataArray['entity']['quizAnswerChoices']; // quizAnswerChoices
count($dataArray['entity']['quizAnswerChoices']); // quizAnswerChoices count

Related

how to get this json output into php array

I want this json output into php array:
{
"data": [
{
"id": "1",
"name": "Roger",
"country": "Switzerland",
"city": "Basel"
},
{
"id": "2",
"name": "Rafael",
"country": "Spain",
"city": "Madrid"
},
]
}
I am trying this:
$arrResult = array();
$arrResult['data'] = array();`
while($row = mysqli_fetch_assoc($result)){`
$id = $row['id'];
$name = $row['name'];
$country = $row['country'];
$arrResult['data'][] = array(
'id'=> $id,
'name'=> $name,
'country'=> $country,
);
}
echo json_encode($arrResult, JSON_FORCE_OBJECT);
I want the same output as given into JSON Format from a php array.
I have found your problem. Remove the comma in the json (explained in the code).
<?php
$json = '{
"data": [
{
"id": "1",
"name": "Roger",
"country": "Switzerland",
"city": "Basel"
},
{
"id": "2",
"name": "Rafael",
"country": "Spain",
"city": "Madrid"
}, <--- THIS IS A PROBLEM
]
}';
/* in order for this function to work you need to delete that comma.
Because there isn't another list in json so comma should not be there */
$arrResult = json_decode($json, true);
print_r($arrResult);
You can use json_decode() if you are using PHP >= 5.2.0
Here is a sample on how to use json_decode()
<?php
// JSON string
$someJSON = '[{"name":"Shriram","gender":"male"},{"name":"Lexa","gender":"female"},{"name":"John Doe","gender":"male"}]';
// Convert JSON string to Array
$someArray = json_decode($someJSON, true);
print_r($someArray); // Dump all data of the Array
echo $someArray[0]["name"]; // Access Array data
// Convert JSON string to Object
$someObject = json_decode($someJSON);
print_r($someObject); // Dump all data of the Object
echo $someObject[0]->name; // Access Object data
?>
you can use the json_decode function.
example;
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
echo $json;
$array = json_decode($json, true);
print_r($array);
?>
What I've understood is that you want to encode your array into the json format shown.
Use json_encode($arrResult) instead of json_encode($arrResult, JSON_FORCE_OBJECT).
JSON_FORCE_OBJECT outputs an object rather than an array.

How to decode this json with foreach

This is the JSON
{
"circuit_list": [
{
"_id": "58c0f378a986f808cdaf94cf",
"aggregation": {
"dev_name": "ME2-D2-BOO",
"port": {
"desc": "AKSES_SITE_SITE-TSEL_ME2-D2-BOO#1/2/5_200M_BOO082#CIPAKUBOO534",
"name": "1/2/5"
}
},
"area": "AREA 2",
"site_id": "N/A",
"site_name": "N/A"
},
{
"_id": "58c0f378a986f808cdaf94d0",
"aggregation": {
"dev_name": "ME2-D2-BOO",
"port": {
"desc": "AKSES_SITE_SITE-TSEL_ME2-D2-BOO#1/2/5_200M_BOO082#CIPAKUBOO534",
"name": "1/2/5"
}
},
"area": "AREA 2",
"site_id": "N/A",
"site_name": "N/A"
}
}
I already try with this code
$json = json_decode($url, true);
foreach($json as $value)
{
$_id = $value->_id;
}
it didn't work. Please help, I need to get the value to show them on the view. Did I do this wrong? this json is difficult because i didn't understand the structure.
I usually decode json with format
[{"id":"1","name":"faisal"}]
like this and with my foreach it's working.
If the second parameter of json_decode is true, the function will return an array instead of an object. Also, you would need to loop over the circuit_list property of the object.
$json = json_decode($url); // <- remove the parameter
foreach($json->circuit_list as $value) // <- loop over circuit_list
{
$_id = $value->_id;
}
<?php
$json = json_decode($url,true);
foreach($json['circuit_list'] as $value)
{
$id = $value['_id'];
}
?>

json object is bahaving wrongly

I am test-running a web application
where in json is required. I have the following json
structure:
{
"Articles": [
{
"Article": {
"ID": 111,
"title": "Idiot",
"author": "Moron",
"pubDate": "11/2/14",
"summary": "bla bla bla"
},
"Article": {
"ID": 222,
"title": "wisdom",
"author": "wise one",
"pubDate": "11/2/15",
"summary": "ha ha ha"
}
}
]
}
I then decided to check if a matching ID exits before adding
any record. To this effect, I wrote a method, encased it within
a JSon class as follows:
public function ID_Exists($ID){
$file = file_get_contents($this->FileName, true);
$data = json_decode($file, false); //get json in array string format
foreach($data as $child){
foreach($child as $item){
if($item->ID == $ID){
echo 'Exists';
}else{
echo 'Non Existent';
}
}
}
}
I test-ran it like:
$Obj = new JSon('file.json'); //knows what to do
if($Obj->ID_Exists(111)){
//ok ! no problem
}else{
////no problem
}
Here's the output I got:
Undefined property: stdClass::$ID in
C:\Server\wamp\www\Oweb\libs\dmanager.php on line 635
What am I doing wrong? I don't want to use the array
format of json_decode().
Your JSON structure is impossible. Articles is an array which contains a single object which contains the key Article twice - this cannot work.
Your structure needs to be:
{
"Articles": [
{
"ID": 111,
...
},
{
"ID": 222,
...
}
]
}
Which you can traverse using:
$data = json_decode($json);
foreach ($data->Articles as $article) {
if ($article->ID == ..) ..
}

PHP: How to get a value from a JSON file?

I'm using PHP and json_decode to use a remote API and I'm having what seems to be a newbie problem for which I didn't even know what to search to find my answer.
So on my script I have a $code = 392 and a json file which simplified version is:
{
"result": {
"items": [
{
"name": "New York",
"code": 7294,
},
{
"name": "Miami",
"code": 392,
},
{
"name": "Los Angeles",
"code": 9182,
}
]
}
}
So, simply put, having the code 392 I want to know which name corresponds to that code. How ?
(The actual json result has thousands of "items", if that makes a difference)
At first you should decode your json data like:
// will decode json data as assoc array
$data = json_decode($json_data, true);
Then, you can get value in this array like:
$item01 = $data['result']['items'][0];
$name = $item01['name']; // New York
$code = $item01['code']; // 7294
Or
// will decode json data as object
$data = json_decode($json_data);
$item01 = $data->result->items[0];
$name = $item01->name; // New York
$code = $item01->code; // 7294
You can iterate through items in result of your JSON object, and check for equality with the desired code, and each item's code. Here's how you would implement it into a function.
function getNameFromCode($json, $code) {
foreach ($json['result']['items'] as $item)
if ($item['code'] == $code)
return $item['name'];
// return false if the code wasn't found.
return false;
}
// assume this is the JSON string of your example.
$json_string = "...";
// pass true as the second argument to get an associative array.
$json = json_decode($json_string, true);
// should return "Los Angeles".
$name = getNameFromCode($json, 9182);
Documenation on foreach().
foreach( json_decode($my_json_string) as $key => $item)
if ( $item['code'] === $code ) { $name = $item[name]; break; }
You can convert JSON to PHP object and loop through the items with foreach loop.
function getNameByCode($phpobj, $code){
if( isset($phpobj->result) ){
if( isset($phpobj->result->items)
&& is_array($phpobj->result->items) ){
foreach($phpobj->result->items as $item){
if( $item->code == $code ){
return $item->name;
}
}
}
}
return false;
}//end function
You can test with this ... NOTE: trailing commas are removed as suggest by rjdown in comment
$json = '{
"result": {
"items": [
{
"name": "New York",
"code": 7294
},
{
"name": "Miami",
"code": 392
},
{
"name": "Los Angeles",
"code": 9182
}
]
}
}';
$phpobj = json_decode($json);
$name = getNameByCode($phpobj, "7294");
echo $name;

Extracting information from an array in php

Can any one tell me how to extract the 'honda' value out of the array below using php?
{
"version": "1.0",
"encoding": "UTF-8",
"entry": {
"name": "bob",
"car": {
"model": "honda"
}
}
}
This looks like a json encoded object. What you could do is:
$info = json_decode($data, true); //where $data has your stuff from the question
$carModel = $obj['entry']['car']['model'];
If you have all that in a variable called "obj", then
$obj = '{ "version": "1.0", "encoding": "UTF-8", "entry": { "name": "bob", "car": { "model": "honda" } } }';
$arr = json_decode($obj, true);
echo $arr['entry']['car']['model'];
should be 'honda'
EDITED: Per Omar below, you do need the true as the second param in json_decode. He should get selected as the correct answer.
Use json_decode as: http://php.net/manual/fr/function.json-decode.php
<?php
$json = '{"version": "1.0","encoding": "UTF-8","entry": {"name": "bob","car": {"model": "honda"} } }';
$tab = json_decode($json, true);
$honda = $tab['entry']['car']['model'];
var_dump($honda);
// or with object:
$obj = json_decode($json);
$honda = $obj->entry->car->model;
var_dump($honda);

Categories