How do I get the output of Apple to be fruit and Beef to be meat with this kind of JSON? Is it even possible to get that data?
P.S. each array's first index will always be 1.
Example of desired output:
Apple -> fruit
Beef -> meat
Celery -> vegetable
{
"Apple": {
"fruit": "1"
},
"Beef": {
"meat" : "1"
},
"Celery": {
"vegetable" : "1"
}
}
You can use json_decode:
$obj = json_decode( $jsonString );
echo $obj->Apple->fruit;
et voila!
PS: Your above JSON is unvalid (maybe a typo): please add a : after "Celery"
PS2: each array's first index is not 1, index(es) are 'Apple', 'Beef' and 'Celery'.
Related
New to PHP (from C#). I have an array ($metaarray), which if I json_encode() to the screen, it has this value:
[
{
"measure":"Walking","record":"steps","latestres":"6870","datet":"2022-08-31"
},{
"measure":"","record":"kilograms","latestres":"117","datet":"2022-09-12"
},{
"measure":"","record":"","latestres":null,"datet":"2022-09-12"
},{
"measure":"Walking","record":"steps","latestres":"6840","datet":"2022-09-12"
},{
"measure":"Bodyweight","record":"kilograms","latestres":"92","datet":"2022-09-12"
},{
"measure":"Benchpress","record":"kilograms","latestres":"90","datet":"2022-09-12"
}
]
Is there an easy way for me to iterate through the metaarray - or to easily reference a record - eg. I would normally do something like:
$latestres = $metaarray[0][2];
...which should be "6870" - however it doesn't return any result when I do that.
Is there a way I can easily reference a particular value (eg. first record, "latestres" or 3rd value) in the above array?
I don't know if this helps you, but $data[2] does not represent third item in an array, unless the array happens to be created linearly (called a list). In PHP, 2 is actually the key to a map (name/value pair). So unless there is actually a key with that index, you can't access it. You can see a demo of what I'm talking about here.
You can get around the feature/limitation by using one of the tricks from this answer: https://stackoverflow.com/a/24825397/231316
function getNthItemFromArray(array $array, int $idx)
{
return $array[array_keys($array)[$idx]];
}
Obviously you'd add some guards.
As everyone notes, you should really start with your data before the encode. However, assuming that for whatever you have a JSON string, you can tell the decoder to give you an associative array instead of an object. Putting that all together you could do something like:
$json = <<<EOT
[
{
"measure":"Walking","record":"steps","latestres":"6870","datet":"2022-08-31"
},{
"measure":"","record":"kilograms","latestres":"117","datet":"2022-09-12"
},{
"measure":"","record":"","latestres":null,"datet":"2022-09-12"
},{
"measure":"Walking","record":"steps","latestres":"6840","datet":"2022-09-12"
},{
"measure":"Bodyweight","record":"kilograms","latestres":"92","datet":"2022-09-12"
},{
"measure":"Benchpress","record":"kilograms","latestres":"90","datet":"2022-09-12"
}
]
EOT;
$decoded = json_decode($json, true);
echo getNthItemFromArray($decoded[0], 2);
function getNthItemFromArray(array $array, int $idx)
{
return $array[array_keys($array)[$idx]];
}
Demo here: https://3v4l.org/POdma
I have the following encoded JSON array
{
"canonList": [{
"deviceId": "Device123",
"deviceModel": "Model123",
"mapList": [{
"alarmStatus": true,
"disabledEndDate": "2020-01-28T15:06:19",
"lastUpdateDate": "2020-01-02T15:06:19",
"ruleDesc": "this is a test description"
}, {
"alarmStatus": true,
"disabledEndDate": "2020-01-28T15:06:19",
"lastUpdateDate": "2020-01-02T15:06:19",
"ruleDesc": "this is a test description 3"
}, {
"alarmStatus": true,
"disabledEndDate": "2020-01-28T15:06:19",
"lastUpdateDate": "2020-01-02T15:06:19",
"ruleDesc": "this is a test description 2"
}]
}, {
"deviceId": "Device1234",
"deviceModel": "Model1234",
"mapList": {
"alarmStatus": true,
"disabledEndDate": "2020-01-28T15:06:19",
"lastUpdateDate": "2020-01-02T15:06:19",
"ruleDesc": "this is a test description 5"
}
}],
"resultCode": 0,
"transactionId": "retrieve_1580400944"
}
I am trying to create an array of just all the values of ruleDesc but I am only getting a null value. The index of the value is dynamic. One thing certain is I need the value inside ruleDesc ...
I've used
$arrayName['canonList']['mapList']['ruleDesc']
but it's only getting the value of the first array.
Any idea?
You need to extract all the mapList entries first, which you can do with array_column. Then you need to check if the maplist value has a ruleDesc key, in which case you add that to your output; otherwise you merge all the ruleDesc from the mapList into the output:
$ruleDesc = array();
foreach (array_column($arrayName['canonList'], 'mapList') as $mList) {
if (isset($mList['ruleDesc'])) {
$ruleDesc[] = $mList['ruleDesc'];
}
else {
$ruleDesc = array_merge($ruleDesc, array_column($mList, 'ruleDesc'));
}
}
print_r($ruleDesc);
Output:
Array
(
[0] => this is a test description
[1] => this is a test description 3
[2] => this is a test description 2
[3] => this is a test description 5
)
Demo on 3v4l.org
As I see you have 2 inner arrays inside your JSON object. The first one is canonList and the second one is mapList so you have to iterate over both of them and add needed values into the result array like this:
$ruleDescs = [];
foreach ($arrayName['cannonList'] as $cannon) {
foreach ($cannon['mapList'] as $map) {
$ruleDescs[] = $map['ruleDesc'];
}
}
print_r($ruleDesc);
Supposed i have an array of object of
$test
[
{
my_string: "ciao",
my_number: 10
},
{
my_string: "ciao b",
my_number: 100
},
{
my_string: "ciao c",
my_number: 100
},
{
my_string: "ciao d",
my_number: 100
},
]
How can i display the third object "ciao c" my_string, my_number in the test $array
I tried but it displays all the data i just want only the third object to display
function obj($array){
foreach ($array as $test){
echo $test->my_string. ' ' .$test->my_number. '<br>';
}
}
the desired output should be
ciao c
100
You can access your object like that,
function obj($array){
echo $array[2]->my_string. ' ' .$array[2]->my_number. '<br>';
}
But your definition of object should be proper to achieve this
If you have an array then you can access it by index of element. "Cannot use object of type stdClass as array" this error says that you try to use stdClass as array (in case when you can try access by index).
I want to return for each vehicule of the API the brand name and the model name
i'm actualy using this loop:
$vehiculecount=count($data);
for($x = 0; $x < $vehiculecount; $x++) {
echo $data[$x];
echo $data[brand][name];
echo "<br>";
}
That actualy return me only :
Array
Array
Array
Array
Array
Array
...
This is what i'm getting in PHP with curl to an API :
{
totalResult: "150",
nbPageList: 2,
createdAt: "2018-05-28T09:23:05+0200",
updatedAt: "2018-05-28T10:55:14+0200",
reference: "5nqts",
reportNumber: 5,
country: "FR",
state: "vehicle.state.parc",
brand: {
reference: "56f50a85cb0f8",
name: "CITROEN"
},
model: {
reference: "57f4d339e38e3",
name: "C3 AIRDREAM BUSINESS"
},
I want to get only 'brand''name' for each vehicle for exemple.
Thx a lot for your help !
First, you should dump, as debugging purpose, the $data object in your loop.
Then, you should see that inside your loop, to acces to an element by its number, you have to use the indexed access like this :
echo $data[$x][brand][name];
Also, to access the brand and name index, you have to use string-key index like this : $data[$x]['brand']['name']
I'm trying to retrieve team1 score however i cant seem to figure out how to output this. So far i've got this to work where $obj is the json output.
$obj->recent
JSON
"recent": [
[
{
"match_id": "64886",
"has_vods": false,
"game": "dota2",
"team 1": {
"score": "",
"name": "Wheel Whreck While Whistling",
"bet": "7%"
},
"team 2": {
"score": "",
"name": "Evil Geniuses DotA2",
"bet": "68%"
},
"live in": "1m 42s",
"title": "Wheel Whreck... 7% vs 68% Evil...",
"url": "",
"tounament": "",
"simple_title": "Wheel Whreck... vs Evil...",
"streams": []
}
]
You need to use json_decode(); This function returns proper object with arrays and objects inside. Now you need check what is an object and what is an array.
$obj = json_decode($obj, true);
$obj->recent; //array
$obj->recent[0]; //first element of array
$obj->recent[0][0]; //first element of second array
$obj->recent[0][0]->{'team 1'}; //access to object team 1
$obj->recent[0][0]->{'team 1'}->score; //access to property of object team 1
You can find this helpful to understand what happens;
You can also check example on json_decode documentation
If you use var_dump function on $obj it will show you what is an array and what is an object.
You'll want to use json_decode to get that into an array. It looks like recent is an array of arrays of objects. So, you'll do something like
$json = json_decode($obj->recent, true);
$team1 = $json[0][0]['team 1']; //should return array
$score = $team1['score']
edit: Thanks for the comment, was missing a true as the second param in json_decode