fetch values from array within an array - php

I have a multidimensional array, i wish to extract each value from this array.
The array is stored in $data.
{"success":true,"categories":
[
{"
category_id":"C1",
"parent_id":"P1",
"name":"N1",
"categories":
[
{
"category_id":"C11",
"parent_id":"P11",
"name":"N11",
},
{
"category_id":"C12",
"parent_id":"P12",
"name":"N12",
},
],
"status":"1"
},
{
category_id":"C2",
"parent_id":"P2",
"name":"N2",
"categories":
[
{
"category_id":"C21",
"parent_id":"P21",
"name":"N21",
[
{
"category_id":"C22",
"parent_id":"P23",
"name":"N24",
}
],
"status":"2"
}
],
"status":"3"
},
]
}
I tried using
$total = $data['categories']['category_id'];
to fetch value C11
but wasn't able to do so.
can anyone tell how i can fetch all the data especially C22

You have to first use json_decode.
$array = json_decode($data, true);
Then you can access the array as you have stated.
Or loop throught the categories:
if (!empty($array)) {
foreach ($array['categories'] as $category) {
echo $category['id'];
}
}
You may have to do this recursively to loop through the categories within the categories. But it depends completely what you want to achieve. A nested loop could do the job if it is always just one level deep.
EDIT
The JSON you have provided is not quite right, I have given a corrected one below:
{
"success": true,
"categories": [
{
"category_id": "C1",
"parent_id": "P1",
"name": "N1",
"categories": [
{
"category_id": "C11",
"parent_id": "P11",
"name": "N11"
},
{
"category_id": "C12",
"parent_id": "P12",
"name": "N12"
}
],
"status": "1"
},
{
"category_id": "C2",
"parent_id": "P2",
"name": "N2",
"categories": [
{
"category_id": "C21",
"parent_id": "P21",
"name": "N21",
"categories": [
{
"category_id": "C22",
"parent_id": "P23",
"name": "N24"
}
],
"status": "2"
}
],
"status": "3"
}
]
}
There were a few trailing commas and missing quote marks.

The data is not in PHP array, its a JSON array. You have to decode it, by using json_decode() function.

That's JSON, not php multidimensional array. You can use json_decode function to read through it.

Related

how can two array marge each inside object key are matching it Cross?

I have two array user and game
$user =[
{
"name": "jone",
"id": "100"
},
{
"name": "Peters",
"id": "200"
}
]
$game = [
{
"name": "tennis",
"level": "05",
"user_id": "100"
},
{
"name": "football",
"level": "03",
"user_id": "100"
},
{
"name": "football",
"level": "05",
"user_id": "200"
}
]
I want to get a result like this using PHP / Laravel
$user = [
{
"name": "jone",
"id": "100"
"game": [
{
"name": "tennis",
"level": "05",
"user_id": "100"
},
{
"name": "football",
"level": "03",
"user_id": "100"
}
],
},
{
"name": "Peters",
"id": "200"
"game": [
{
"name": "football",
"level": "05",
"user_id": "200"
}
],
}
],
any one help me
I understand that I should not provide an answer to this "non-question". I still do so, as I think it might carry some learning value.
The idea is, not to cycle each game for each user (as the naive approach would be), as this simply doesn't scale. It is much better to use a matching array and then sort the games into it:
//Prepare matching array
$user_games=array();
foreach ($user as $u) {
$u['game']=array();
$user_games[$u['id']]=$u;
}
//Sort games into matching array
foreach ($game as $g) {
$user_games[$g['user_id']]['game'][]=$g;
}
This way a new game will not create n cycles (n being the number of users), but only one.
print_r($user_games);
creates the desired output. If the user IDs as indices are a problem, just use
print_r(array_values($user_games);

PHP json_encode string key as array

i write a api for my games to get achievements and so on. i load the data from a webserver into unity c# over a www request. i need a array from php which contain achievements and more data. the problem is, the result is this
[
{"ID":"1",
"gameID":"1",
"name":"achv1",
"neededvalue":"50",
"player_achievements":{
"ID":"8",
"achievementID":"1",
"playerID":"9",
"value":"",
"completed":""
}
},
{"ID":"2",
"gameID": "1",
"name":"achv2",
"neededvalue":"100",
"player_achievements":{
"ID":"9",
"achievementID":"2",
"playerID":"9",
"value":"","completed":""
}
}
]
the player_achievements is a child array of the head array and i need the square_brackets around the player_achievements [] because untity c# cannot convert it to an object. i search hours for finding a solution but nobody explain how. i found this link but this is not a option for me. i want the string keys and not numbers. give it a way to use the string keys as array and not as object ?
i need it like so:
[
{ "ID":"1",
"gameID":"1",
"name":"achv1",
"neededvalue":"50",
"player_achievements":[
{ "ID":"8",
"achievementID":"1",
"playerID":"9",
"value":"",
"completed":""
}
]
},
{
"ID":"2",
"gameID":"1",
"name":"achv2",
"neededvalue":"100",
"player_achievements":[
{ "ID":"9",
"achievementID":"2",
"playerID":"9",
"value":"",
"completed":""
}
]
}
]
If I am reading your question correctly, you need to make the player_achievements element an array containing the original value of that element.
<?php
$json = <<<END
[
{"ID":"1",
"gameID":"1",
"name":"achv1",
"neededvalue":"50",
"player_achievements":{
"ID":"8",
"achievementID":"1",
"playerID":"9",
"value":"",
"completed":""
}
},
{"ID":"2",
"gameID": "1",
"name":"achv2",
"neededvalue":"100",
"player_achievements":{
"ID":"9",
"achievementID":"2",
"playerID":"9",
"value":"","completed":""
}
}
]
END;
$data = json_decode($json, true);
for($i=0;$i<sizeof($data);$i++)
{
$data[$i]['player_achievements'] = [$data[$i]['player_achievements']];
}
echo json_encode($data);
This produces a structure like the one you say you need.
[
{
"ID": "1",
"gameID": "1",
"name": "achv1",
"neededvalue": "50",
"player_achievements": [
{
"ID": "8",
"achievementID": "1",
"playerID": "9",
"value": "",
"completed": ""
}
]
},
{
"ID": "2",
"gameID": "1",
"name": "achv2",
"neededvalue": "100",
"player_achievements": [
{
"ID": "9",
"achievementID": "2",
"playerID": "9",
"value": "",
"completed": ""
}
]
}
]
I found an answer, I add a zero before the child element as key of array.

Remove instance of square brackets, if found two successive instances

I have a data in following manner:
{"id": "sugarcrm", "text": "sugarcrm", "children": [ [ { "id": "accounts", "text": "accounts", "children": [ { "id": "id", "text": "id" }, { "id": "name", "text": "name" } ] } ] ] }
Now, I want to remove the instance of square bracket i.e. [ and ] if there are two successive instances like this [ [ or ] ].
Now if you see the above data, you'll get to see that there are instances of [ and ] which are repeated twice successively. So I want to remove one instance of each.
Now, I can check the two successively repeated instances of each and remove one, like this
$text = '{"id": "sugarcrm", "text": "sugarcrm", "children": [ [ { "id": "accounts", "text": "accounts", "children": [ { "id": "id", "text": "id" }, { "id": "name", "text": "name" } ] } ] ] }';
echo preg_replace('/\[ \[+/', '[', $text);
Now, the above code is for [. So to remove the successively repeated instance of ], I'll have to repeat the same code again.
I want to know, is there a better way to achieve the same result or not. Meanwhile, I can work it out, but still what if, in future, I'll have to do the same for any other character? Kindly guide me here.
You are processing a json string. It is contraindicated to attempt string manipulations (with regex or other) because there are very possible pitfalls with "over-matching".
While I don't fully understand the variability of your data structure, I can provide some temporary guidance by converting your json string to an array and then safely modifying the data with an array function.
Consider this:
Code: (Demo)
$json='{"id": "sugarcrm", "text": "sugarcrm", "children": [ [ { "id": "accounts", "text": "accounts", "children": [ { "id": "id", "text": "id" }, { "id": "name", "text": "name" } ] } ] ] }';
$array=json_decode($json,true); // convert to array
foreach($array as &$a){ // $a is modifiable by reference
if(is_array($a) && isset($a[0]) && isset($a[0][0])){ // check if array and if two consecutive/nested indexed subarrays
$a=array_column($a,0); // effectively shift deeper subarray up one level
}
}
$json=json_encode($array);
echo $json;
Output:
{"id":"sugarcrm","text":"sugarcrm","children":[{"id":"accounts","text":"accounts","children":[{"id":"id","text":"id"},{"id":"name","text":"name"}]}]}
For that matter, if you know where the double-nested-indexes are, then you can access them without looping (or modifying by reference) like this:
$json='{"id": "sugarcrm", "text": "sugarcrm", "children": [ [ { "id": "accounts", "text": "accounts", "children": [ { "id": "id", "text": "id" }, { "id": "name", "text": "name" } ] } ] ] }';
$array=json_decode($json,true);
$array['children']=array_column($array['children'],0); // modify 2 known, nested, indexed subarrays
$json=json_encode($array);
echo $json;
How about:
echo str_replace(array('[ [', '] ]'), array('[', ']'), $text);

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