Extracting json object from array - php

I am using php/Laravel and i have a response from an API that returns the following format in my controller:
[
{
"id": "474",
"room_id": "14",
"user_id": "20",
"name": "121001.webm",
"fname": "",
"status": "0",
"date_recorded": "October 17 2018 07:18:51",
"size": "396135",
"is_public": "0",
"allow_download": "0",
"privatekey": "",
"duration": "0",
"record_path": "https:example/url/test.mp4",
"record_url": "https:example/url/test.mp4"
}
]
I believe this is an array inside of the array is the json object i want the data from, so for example I want the record id.
I have used these solutions with no luck :
$response->record_url;
$response[0]->record_url;
also tried to encode or decode the $response
Any help would be greatly appreciated

In JSON string, you have and array with one element being an object.
Now, depending on how you're decoding it, you'll get in PHP and array with stdClass object, or array with associative array inside.
//this will return array with stdClass object
$data = json_decode($json);
echo $data[0]->record_url;
//this will return array with associative array
$data = json_decode($json, true);
echo $data[0]['record_url'];
Working code: https://3v4l.org/TJNQ1

Try this code
var_dump(json_decode($response)->record_url);

Please refer the below program and respective output:
$json = '[
{
"id": "474",
"room_id": "14",
"user_id": "20",
"name": "121001.webm",
"fname": "",
"status": "0",
"date_recorded": "October 17 2018 07:18:51",
"size": "396135",
"is_public": "0",
"allow_download": "0",
"privatekey": "",
"duration": "0",
"record_path": "https:example/url/test.mp4",
"record_url": "https:example/url/test.mp4"
}
]';
$array1 = json_decode($json, false);
echo $array1[0]->id //This will print the value of id which is 474.
$array2 = json_decode($json, true);
echo $array2[0]['id'] // This will also print th evalue of id which is 474.
The second parameter of the function json_decode is boolean when TRUE, returned objects will be converted into associative arrays.
Thanks

Related

How to get specific data on a multi dimension array in JSON format [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
I have this multi dimension array in JSON format.
{
"CUSTOMER_ORDER":
[
{
"customer_number": "51",
"table_no": "7",
"menu_name": "Fried Chicken",
"menu_quatity": "5",
"menu_price": "200",
"order_total_price": "1000"
},
{
"customer_number": "51",
"table_no": "7",
"menu_name": "Fries",
"menu_quatity": "5",
"menu_price": "200",
"order_total_price": "1000"
}
]
}
My question is that how do I get specific data on index 0 of CUSTOMER_ORDER?
For example I want to get the menu_name which is Fried Chicken, Thanks.
Update
I am having trouble after decoding the JSON data, what I get is this:
json_decode() expects parameter 1 to be string, array given
when I used this:
$json_data = $this->post('CUSTOMER_ORDER');
$json_decoded = json_decode($json_data);
$customer_nickname = $json_decoded->CUSTOMER_ORDER[0]->customer_nickname;
and this when I try this:
Undefined index: CUSTOMER_ORDER
$json_decoded = json_decode($json_data,true);
or
$json_decoded = json_decode(json_encode($json_data),true);
$customer_nickname = $json_decoded['CUSTOMER_ORDER'][0]['customer_nickname'];
By the way I am using CodeIgniter 3. I hope someone help me. Thanks.
I hope it helps.
$json = '{
"CUSTOMER_ORDER":
[
{
"customer_number": "51",
"table_no": "7",
"menu_name": "Fried Chicken",
"menu_quatity": "5",
"menu_price": "200",
"order_total_price": "1000"
},
{
"customer_number": "51",
"table_no": "7",
"menu_name": "Fries",
"menu_quatity": "5",
"menu_price": "200",
"order_total_price": "1000"
}
]
}';
$jsonDecodedArray = json_decode($json);
print_r($jsonDecodedArray->CUSTOMER_ORDER[0]->customer_number);
// OUTPUT 51

How to add new key with new value to exist array in php ?

i'm trying to add value with key to exist array
this my array
{
"object": {
"USER_ID": "1",
"EMAIL": "abdabughazaleh#hotmail.com",
"FIRST_NAME": "abd",
"LAST_NAME": "abughazaleh",
"PICTURE": "images/users/xuhEzR6m4LvjCuKx1vAb.jpg"
}
}
with json result .
i need to add element like this :
{
"object": {
"USER_ID": "1",
"EMAIL": "abdabughazaleh#hotmail.com",
"FIRST_NAME": "abd",
"LAST_NAME": "abughazaleh",
"PICTURE": "images/users/xuhEzR6m4LvjCuKx1vAb.jpg",
"new_key": "new_value"
}
}
when i trying this :
array_push($ar['object'],array('new_key'=>'new_value'));
and this :
$ar['object']['new_key'] = 'new_value';
problem not solved for me :(
This is not an array, this is json:
{
"object": {
"USER_ID": "1",
"EMAIL": "abdabughazaleh#hotmail.com",
"FIRST_NAME": "abd",
"LAST_NAME": "abughazaleh",
"PICTURE": "images/users/xuhEzR6m4LvjCuKx1vAb.jpg"
}
}
First, convert json into associative array with json_decode:
$json = '{
"object": {
"USER_ID": "1",
"EMAIL": "abdabughazaleh#hotmail.com",
"FIRST_NAME": "abd",
"LAST_NAME": "abughazaleh",
"PICTURE": "images/users/xuhEzR6m4LvjCuKx1vAb.jpg"
}
}';
$json = json_decode($json, true); //true second parameter is actully for converting json into associative array
Than add a value to newly created array:
$json['object']['key'] = 'value';
Result of print_r($json):
Array
(
[object] => Array
(
[USER_ID] => 1
[EMAIL] => abdabughazaleh#hotmail.com
[FIRST_NAME] => abd
[LAST_NAME] => abughazaleh
[PICTURE] => images/users/xuhEzR6m4LvjCuKx1vAb.jpg
[key] => value
)
)
Than convert back to json:
$json = json_encode($json);
Reult of echo $json;:
{
"object":{
"USER_ID":"1",
"EMAIL":"abdabughazaleh#hotmail.com",
"FIRST_NAME":"abd",
"LAST_NAME":"abughazaleh",
"PICTURE":"images\/users\/xuhEzR6m4LvjCuKx1vAb.jpg",
"key":"value"
}
}
I solve it using this code ,
<?php $array->object->new_key ='new_value'; ?>

Json decoding and reading

I want to make a script to share GameServers stats. I'm using JSON method. How can I read only hostname?
JSON
[
[
{
"ip": "176.57.188.22",
"port": "27022",
"rank": "1",
"online": "1",
"hostname": "..:: LS Public Server ::.. #1",
"num_players": "12",
"max_players": "32",
"location": "AL",
"mapa": "de_dust2"
}
],
true
]
or link to test it LIVE HERE
I wat to read only hostname. I tried too muany methods, but they don't work for me.
Let's suppose the JSON string (or object) is stored in the variable $json.
<?php
// convert your JSON object to a PHP array
$decoded_json = json_decode($json, true);
print_r($decoded_json); // print your PHP array to check how to subindex your new var
// I think it will be something like $decoded_json[0]['hostname']
?>
<?php
$test = '[
[
{
"ip": "176.57.188.22",
"port": "27022",
"rank": "1",
"online": "1",
"hostname": "..:: LS Public Server ::.. #1",
"num_players": "12",
"max_players": "32",
"location": "AL",
"mapa": "de_dust2"
}
],
true
]';
$test = json_decode($test);
echo $test[0][0]->hostname;
//---output---
//..:: LS Public Server ::.. #1
?>
Use json_decode with true as second parameter, it gives you an associative array and it will convert the JSON object into a PHP array.
Try this :
<?php
error_reporting(0);
$test = '[
[
{
"ip": "176.57.188.22",
"port": "27022",
"rank": "1",
"online": "1",
"hostname": "..:: LS Public Server ::.. #1",
"num_players": "12",
"max_players": "32",
"location": "AL",
"mapa": "de_dust2"
}
],
true
]';
$data = json_decode($test,true);
foreach ($data as $info) {
foreach ($info as $result) {
echo $result[hostname];
}
}
?>
Demo!

Easiest way of accessing deep-nested value in json response?

I have the following response (I cut the extra short):
{
"meta": {
"current_page": "1",
"last_page": "1",
"per_page": "15",
"total": "1",
"from": "1",
"to": "1"
},
"Products": [
{
"archived": "0",
"committed_stock": "0",
"created_at": "2015-05-10T17:39:53+00:00",
"deleted": "0",
"description": "desc",
"id": "43061710",
"links": {
"Users": [
{
"id": "107534",
"type": "created_by"
}
],
"Attributes": [
{
"id": "31538870"
}
]
}
}
]
}
Everytime I get this response, there will only be one item in "Attributes." What is the easiest way of grabbing this value? So far I have this:
$json = json_decode($json_data);
$json = json_decode($json_data, true);
echo $json["Products"][0]["links"]["Attributes"][0]["id"];
try this:
var_dump( $json->Products[0]->links->Attributes);
the object field could be ether also an object, or an array:
refer to field: $object->object
refer to array's i cell: $object->array[i]
P.S.
please edit the json, it's missing it's end...
You may also want to try some JSON Path libs for PHP: https://github.com/Peekmo/JsonPath

FuelPHP + JSON + Ajax

For example, when I use Model_Trabalhos::query()->related('categoria'), I Get a normal JSON like this:
{
"id": "1",
"categoria_id": "2",
"empresa": "Veja",
"nome": "Veja",
"thumb_pequena": "jobs/digital/veja/thumb.jpg",
"thumb_grande": "jobs/digital/veja/thumb_grande.jpg",
"destaque": "0",
"categoria": {
"id": "2",
"titulo": "Digital"
},
"imagens": {
"1": {
"id": "1",
"url": "jobs/digital/veja/1.png",
"legenda": "",
"job_id": "1"
},
"2": {
"id": "2",
"url": "jobs/digital/veja/2.png",
"legenda": "",
"job_id": "1"
}
}
}
instead, I wanted to receive back this:
[
{
"id": "3",
"categoria_id": "2",
"empresa": "Valor Econômico",
"nome": "Novo Site",
"thumb_pequena": "jobs/digital/valor-economico/thumb.jpg",
"thumb_grande": "jobs/digital/valor-economico/thumb_grande.jpg",
"destaque": "1",
"categoria": {
"id": "2",
"titulo": "Digital"
},
"imagens": [
{
"id": "3",
"url": "jobs/digital/valor-economico/1.png",
"legenda": "",
"job_id": "3"
}
]
}
]
You see? In the second case, it's wrapped in an array, and I wanted to know if there's a function in FuelPHP native that wrap the content to be ordered.
I'm in trouble... I'm using FuelPHP + ORM to get all my records from a database and generating a JSON to use with JavaScript and Ajax, but in Chrome, the JSON is not following the order by defined, is there any workaround for this problem?
If you're wanting your information in a certain way you could follow that query with a foreach loop that would add them to an array of arrays (translated to an array of JSON objects) once converted to JSON.
$query = Model_Trabalhos::query()->related('categoria')
$categories = array();
foreach ($query as $category) {
$categories[] = array(
'id' => $category->id,
...
);
}
return $categories;
It's an old question, but i had the same problem now and colud resolve like the answer that i posted in https://stackoverflow.com/a/34242106/5670195.
In case it is a function that converts into simple array, the objects returned as the relationship of ORM.

Categories