How do I create a JSON-encoded 2D array? - php

I'm trying to create a two-dimensional array with the following code, but it gets JSON-encoded as an object. How do I fix this?
$result = $bd->query("select * from contenidos where idfolleto=$idf order by fila");
$arr = array();
if ($result) {
while ($row = mysqli_fetch_object($result)) {
$filaAct = $row->fila;
$arr[$filaAct][] = (array) $row;
}
}
echo json_encode($arr);
The output is:
{
"1": [{
"id": "6",
"idfolleto": "1",
"fila": "1",
"orden": "1",
"tipo": "carrousel",
"titulo": "",
"subtitulo": null,
"color1": null,
"color2": null,
"color_fondo": null
}],
"2": [{
"id": "7",
"idfolleto": "1",
"fila": "2",
"orden": "1",
"tipo": "texto-imagenes",
"titulo": "Texto 1",
"subtitulo": null,
"color1": null,
"color2": null,
"color_fondo": null
}, {
"id": "8",
"idfolleto": "1",
"fila": "2",
"orden": "2",
"tipo": "texto-imagenes",
"titulo": "Texto 2",
"subtitulo": null,
"color1": null,
"color2": null,
"color_fondo": null
}],
"3": [{
"id": "9",
"idfolleto": "1",
"fila": "3",
"orden": "3",
"tipo": "texto-imagenes",
"titulo": "Texto 3",
"subtitulo": null,
"color1": null,
"color2": null,
"color_fondo": null
}]
}

You would have to index it without using your own defined indices.
If you must maintain using fila as the indices then you have to understand that the encoded JSON will be an object. You can json_decode it back into an array though like: json_decode($json, 1);
Otherwise before encoding the array you could call: $arr = array_values($arr); which would result in the array being encoded as a JSON array once you call json_encode.

If you're sure that your fila fields will contain "indexes" (I mean continuous integers starting from 0), then you can convert them to integers using intval.
if ($result) {
while ($row = mysqli_fetch_object($result)) {
$arr[intval($row->fila)][] = (array) $row;
}
}
Otherwise, it probably would be better to just group the records and create an array of the groups.
if ($result) {
$groups = array();
while ($row = mysqli_fetch_object($result)) {
$groups[$row->fila][] = (array) $row;
}
$arr = array_values($groups);
}

Related

Create parent child relation JSON tree

This is my code I have three table posts table, comments table, and likes table. I have a left joined all three tables with postid common in all three tables. I'm getting all data perfectly but I'm getting repeating data of postdata (ex: Postid=1) I don't want that. My problem is getting repeating data of Postdata (ex: Postid=1) I want to make a parent of Postdata where postsdata=1 and I want to insert all data into parent
<?php
include "../dcon.php";
$sql = "select * FROM posts left join comments on comments.Cpostid=posts.PostId left join likes on likes.postid=posts.PostId";
$query=mysqli_query($mysqli,$sql);
$result = mysqli_num_rows($query);
$menus=array();
for($i=0; $i<$result; $i++){
$row = mysqli_fetch_all($query,MYSQLI_ASSOC);
foreach($row as $index => $row ){
$menus[]=[
'PostId'=>$row['PostId'],
'PostVideo'=>$row['PostVideo'],
'PostDesc'=>$row['PostDesc'],
'PostImage'=>$row['PostImage'],
'PostedBy'=>$row['PostedBy'],
'UserName'=>$row['UserName'],
'Status'=>$row['Status'],
'PostParent'=>$row['PostParent'],
'likes'=>$row['likes'],
'comments'=>[
$index => [
'commentsid'=>$row['commentsId'],
'comments'=>$row['comments'],
'Cpostid'=>$row['Cpostid'],
'time'=>$row['time'],
],],
'likes'=>[
$index =>[
'Likeid'=>$row['Lid'],
'dislikes'=>$row['dislikes'],
'postid'=>$row['postid'],
'userid'=>$row['userid'],
]]
];
}
}
echo json_encode($menus,JSON_PRETTY_PRINT);
?>
My output was below:
[
{
"PostId": "1",
"PostVideo": "v2.mp4",
"PostDesc": "this is a tutorial on bench press",
"PostImage": "null",
"PostedBy": "Irfan khan",
"UserName": "irfan",
"Status": "1",
"PostParent": null,
"likes": {
"Likeid": "1",
"dislikes": "0",
"postid": "1",
"userid": "1"
},
"comments": {
"commentsid": "1",
"comments": "awesome video",
"Cpostid": "1",
"time": "2020-12-16 17:33:33"
}
},
{
"PostId": "1",
"PostVideo": "v2.mp4",
"PostDesc": "this is a tutorial on bench press",
"PostImage": "null",
"PostedBy": "Irfan khan",
"UserName": "khan",
"Status": "1",
"PostParent": null,
"likes": {
"Likeid": "1",
"dislikes": "0",
"postid": "1",
"userid": "1"
},
"comments": {
"commentsid": "2",
"comments": "good workouts",
"Cpostid": "1",
"time": "2020-12-16 17:33:33"
}
},
{
"PostId": "1",
"PostVideo": "v1.mp4",
"PostDesc": "Chicken generally includes low fat in the meat itself (castrated roosters excluded). The fat is highly concentrated on the skin. A 100g serving of baked chicken breast contains 4 grams of fat and 31 grams of protein, compared to 10 grams of fat and 27 grams of protein for the same portion of broiled, lean skirt steak.",
"PostImage": "im1",
"PostedBy": "Rehmat",
"UserName": null,
"Status": "1",
"PostParent": null,
"likes": {
"Likeid": "20",
"dislikes": "0",
"postid": "1",
"userid": "4"
},
"comments": {
"commentsid": null,
"comments": null,
"Cpostid": null,
"time": null
}
},
{
"PostId": "1",
"PostVideo": "v1.mp4",
"PostDesc": "Chicken generally includes low fat in the meat itself (castrated roosters excluded). The fat is highly concentrated on the skin. A 100g serving of baked chicken breast contains 4 grams of fat and 31 grams of protein, compared to 10 grams of fat and 27 grams of protein for the same portion of broiled, lean skirt steak.",
"PostImage": "im1",
"PostedBy": "Rehmat",
"UserName": null,
"Status": "1",
"PostParent": null,
"likes": {
"Likeid": "26",
"dislikes": "0",
"postid": "1",
"userid": "4"
},
"comments": {
"commentsid": null,
"comments": null,
"Cpostid": null,
"time": null
}
},
{
"PostId": "3",
"PostVideo": null,
"PostDesc": "this is an image of chicken",
"PostImage": "post.jpg",
"PostedBy": "khan",
"UserName": null,
"Status": "0",
"PostParent": null,
"likes": {
"Likeid": null,
"dislikes": null,
"postid": null,
"userid": null
},
"comments": {
"commentsid": null,
"comments": null,
"Cpostid": null,
"time": null
}
},
{
"PostId": "9",
"PostVideo": null,
"PostDesc": "gdhgh",
"PostImage": "ghghdf",
"PostedBy": null,
"UserName": null,
"Status": null,
"PostParent": null,
"likes": {
"Likeid": null,
"dislikes": null,
"postid": null,
"userid": null
},
"comments": {
"commentsid": null,
"comments": null,
"Cpostid": null,
"time": null
}
}
];
I want my output like below:
{
"PostId": "1",
"PostVideo": "v2.mp4",
"PostDesc": "this is a tutorial on bench press",
"PostImage": "null",
"PostedBy": "Irfan khan",
"UserName": "irfan",
"Status": "1",
"PostParent": null,
"likes":
'0':{
"Likeid": "1",
"dislikes": "0",
"postid": "1",
"userid": "1"
},
'1':{
"Likeid": "1",
"dislikes": "0",
"postid": "1",
"userid": "1"
},
'2':{
"Likeid": "1",
"dislikes": "0",
"postid": "1",
"userid": "1"
},
'3':{
"Likeid": "1",
"dislikes": "0",
"postid": "1",
"userid": "1"
},
"comments":
'0':{
"commentsid": "1",
"comments": "awesome video",
"Cpostid": "1",
"time": "2020-12-16 17:33:33"
},
'1':{
"commentsid": "1",
"comments": "awesome video",
"Cpostid": "1",
"time": "2020-12-16 17:33:33"
},
'2':{
"commentsid": "1",
"comments": "awesome video",
"Cpostid": "1",
"time": "2020-12-16 17:33:33"
},
'3':{
"commentsid": "1",
"comments": "awesome video",
"Cpostid": "1",
"time": "2020-12-16 17:33:33"
}
},
{
"PostId": "9",
"PostVideo": null,
"PostDesc": "gdhgh",
"PostImage": "ghghdf",
"PostedBy": null,
"UserName": null,
"Status": null,
"PostParent": null,
"likes": {
"Likeid": null,
"dislikes": null,
"postid": null,
"userid": null
},
"comments": {
"commentsid": null,
"comments": null,
"Cpostid": null,
"time": null
}
}
Hmm... At first I thought that your loops were the problem, and you misunderstood the behavior. But then I saw your "i want my output like below", and that didn't made sense, specifically you wanting duplicate likes/comments.
First, the loops: a for loop and an inner foreach loop. The for loop iterates over the number of results. The inner foreach loop iterates over all the results. So if we have 6 results, instead of only iterating 6 times, we iterate 36 times (6 result count x 6 results).
We actually need only 1 loop:
$query = mysqli_query($mysqli, $sql);
$menus = [];
$rows = mysqli_fetch_all($query, MYSQLI_ASSOC);
foreach ($rows as $index => $row) {
$menus[] = [
...
];
}
Next, we avoid duplicate posts by indexing the $menus with PostId. If the PostId does not yet exist in $menus, we insert the post; otherwise we just append the like/comment:
$query = mysqli_query($mysqli, $sql);
$menus = [];
$rows = mysqli_fetch_all($query, MYSQLI_ASSOC);
foreach ($rows as $row) {
if (!isset($menus[$row['PostId']])) {
$menus[$row['PostId']] = [
'PostId' => $row['PostId'],
...
'comments' => [],
'likes' => [],
];
}
$menus[$row['PostId']]['comments'][] = [
...
];
$menus[$row['PostId']]['likes'][] = [
...
];
}
If for some reason you don't want the $menus indexed by PostId, we can just call array_values() after the loop to re-index it with zero-based sequential integer:
foreach (...) { ... }
$menus = array_values($menus);
As for the duplicate likes/comments, you were explicit about it. But just in case you actually want non-duplicate, we can also index them by their Likeid and commentsid, and insert/ignore as necessary:
$query = mysqli_query($mysqli, $sql);
$menus = [];
$rows = mysqli_fetch_all($query, MYSQLI_ASSOC);
foreach ($rows as $row) {
if (!isset($menus[$row['PostId']])) {
$menus[$row['PostId']] = [
'PostId' => $row['PostId'],
...
'comments' => [],
'likes' => [],
];
}
if (!isset($menus[$row['PostId']]['comments'][$row['commentsid']])) {
$menus[$row['PostId']]['comments'][$row['commentsid']] = [
...
];
}
if (!isset($menus[$row['PostId']]['Likes'][$row['Lid']])) {
$menus[$row['PostId']]['Likes'][$row['Lid']] = [
...
];
}
}
And if we also don't want the comments/likes indexed by commentsid/Lid, we can call array_values() on them as well:
foreach (...) { ... }
$menus = array_values($menus);
foreach ($menus as &$menu) {
$menu['comments'] = array_values($menu['comments']);
$menu['likes'] = array_values($menu['likes']);
}
unset($menu);
// Or
array_walk($menus, function (&$menu) {
$menu['comments'] = array_values($menu['comments']);
$menu['likes'] = array_values($menu['likes']);
});

Getting information from nested arrays php

I am making calls to an API
I have the response as an associative array so that I can use:
$field = $response['nameOfKey'];
However, some of the values for keys are themselves arrays like the following:
{
"Title": "Mr",
"Forenames": "Steve",
"Surname": "Williams",
"CountryOfBirth": 1,
"EmailAddress": "john.doe#email.com",
"EmailType": "Personal",
"BirthDate": "\/Date(632880000000)\/",
"Suffix": null,
"NationalInsuranceNumber": null,
"PrimaryAddress": {
"Address1": "Flat 1",
"Address2": "Oxford Street",
"City": "London",
"County": "London",
"Postcode": "L12456",
"Country": 1
},
"AdditionalAddresses": [
{
"Address1": null,
"Address2": null,
"City": null,
"County": null,
"Postcode": null,
"Country": 0,
"AddressType": 0
}
],
"PrimaryTelephone": {
"Number": "123456789",
"DialingCode": 1,
"TelephoneType": 1
},
"AdditionalTelephone": [
{
"Number": "223456789",
"DialingCode": 2,
"TelephoneType": 2
}
],
"BankAccount": {
"AccountName": "John Doe Account",
"AccountNumber": "123456789",
"SortCode": "123456"
},
"PrimaryCitizenship": {
"CountryOfResidency": 1,
"TaxIdentificationNumber": "AB12CD34EF56"
},
"AdditionalCitizenship": [
{
"CountryOfResidency": 0,
"TaxIdentificationNumber": null
}
],
"ExternalCustomerId": "91",
"ExternalPlanId": "91",
"PlanType": 10
}
So at the moment to get Forename I can just do $forename = $decodedResponse["Forenames"]; but I'm quite baffled at trying to get values from the inner arrays.
I thought I could do something like this:
foreach($decodedResponse as $data)
{
foreach($data['TelephoneNumbers'] as $tel)
{
echo $tel['Number']; die();
}
}
Essentially loop through the original Associative array and then loop through a specific key to get its values.
Your should use foreach for following array items: AdditionalAddresses, AdditionalTelephone and AdditionalCitizenship. Otherwise just chain array keys. See examples:
$forename = $decodedResponse['Forenames'];
$address2 = $decodedResponse['PrimaryAddress']['Address2'];
foreach ($decodedResponse['AdditionalTelephone'] as $tel) {
echo $tel['Number'];
}

List multi dimentional array

I have done a query for getting all data's under same id from other table.There are more than 2 data's under same id.
I need to display all data 's under same id like an array.
Here is my sql query:
"SELECT incident.*,entry.*,fighter.*
FROM register_incident AS incident JOIN
register_entry_points AS entry
ON entry.incident_id = incident.incident_id
JOIN add_fire_fighters AS fighter
ON entry.entrypoint_id = fighter.entry_point_id
WHERE incident.incident_id=:incident_id"
I get a response like,
"data":[
{
"incident_id": "5",
"user_id": null,
"entrypoint_id": "20",
"entry_points": "New Entry1111",
"comments": "Comment1",
"fighter_id": "67",
"entry_point_id": "20",
"cylpressure": null,
"time_in": null,
"time_out": null,
"duration": null,
"notes": null
},
{
"incident_id": "5",
"user_id": "16",
"entrypoint_id": "20",
"entry_points": "New Entry1111",
"comments": "Comment1",
"fighter_id": "68",
"entry_point_id": "20",
"cylpressure": "300",
"time_in": "10:30:00",
"time_out": "11:45:00",
"duration": "01:15",
"notes": "Test"
},
But i need to display it like,
"data": [
{
"incident_id": "5",
"user_id": null,
"entrypoint_id": "20",
"entry_points": "New Entry1111",
"comments": "Comment1",
"fighter":{
{
"fighter_id": "67",
"entry_point_id": "20",
"cylpressure": null,
"time_in": null,
"time_out": null,
"duration": null,
"notes": null
},
{
"fighter_id": "68",
"entry_point_id": "20",
"cylpressure": null,
"time_in": null,
"time_out": null,
"duration": null,
"notes": null
}
}
}]
How it is possible?
If I get a ResultSet out of a Query with one or more 1:n relationships, I take the result like this sample.
$Result = array();
foreach($Records as $Record) {
// key 1
$key1 = $Record['incident_id'];
if(isset($Result[$key1])) {
$cuIncident=$Result[$key1];
}
else {
$cuIncident=array(
'incident_id' => $key1,
'user_id' => $Record['user_id'],
//......
'fighter' => array()
);
$Result[$key1] = $cuIncident;
}
// key 2
$key2 = $Record['fighter_id'];
if(isset($cuIncident['fighter'][$key2])) {
$cuFighter = $cuIncident['fighter'][$key2];
}
else {
$cuFighter = array(
'fighter_id' => $key2,
'entry_point_id' => $Record['entry_point_id'],
//......
'key3array' => array()
);
$cuIncident['fighter'][$key2] = $cuFighter;
}
// key 3
// ....
If a key is a multi value key, you have to combine these keys like:
$key3 = $Record['key3prop1']."/".$Record['key3prop2'];
if(isset($key3Array[$key3])) ......

How to access child array key value pair in Laravel controller?

My response code :
Shpping : [
{
"id": "1",
"name": "Dress",
"deleted_at": null,
"created_at": null,
"updated_at": null,
"minicomp": [
{
"id": "1",
"cname": "basic",
"base_id": 44
},
{
"id": "2",
"cname": "Shirt",
"base_id": 177444
},
{
"id": "3",
"cname": "Pants",
"base_id": 444
}
]
}
];
I want to access base_id of of every object in child array 'minicomp' whose parent is 'Shipping'. How can I access it?
First convert your json into array using json_decode().Like this..
$json =<your json>;
$array = json_decode($json,true);
Then
echo $array['Shpping '][0]]['minicomp'][0]['id'];//outputs 1
Example:
<?php
$json = '[{
"id": "1",
"name": "Dress",
"deleted_at": null,
"created_at": null,
"updated_at": null,
"minicomp": [{
"id": "1",
"cname": "basic",
"base_id": 44
}, {
"id": "2",
"cname": "Shirt",
"base_id": 177444
}, {
"id": "3",
"cname": "Pants",
"base_id": 444
}]
}]';
$array = json_decode($json,true);
//print_r($array);
$minicomp = $array[0]['minicomp'];
echo $minicomp[0]['id'];
echo $minicomp[1]['id'];
?>
UPDATE
For getting all ids.Without defining indexes.Use foreach loop:
foreach($minicomp as $key=>$value){
echo $minicomp[$key]['id']."<br/>";
}

PHP loop through data from JSON string

I want to get ItemCategory->id's for each Item->id
How can I do it in the best way?
Here is a part of JSON data item
"6": {
"Item": {
"id": "6",
"name": "test",
"description": "description",
},
"ItemThumbnail": null,
"ItemCategory": {
"3": {
"id": "3",
"name": "name",
"status": "active",
"date_created": "2015-07-07 11:23:52",
"date_updated": "0000-00-00 00:00:00",
},
"4": {
"id": "4",
"name": "name",
"status": "active",
"date_created": "2015-07-07 11:23:52",
"date_updated": "0000-00-00 00:00:00",
}
},
"ItemGroup": []
},
You can convert your json string to a PHP array using $array = json_decode($str, true);, then loop your array and extract the information you need.
See http://php.net/manual/en/function.json-decode.php for more detail on json_decode
After json decode use this.
foreach($Item as $Items)
{
$ItemCategory = $Items->ItemCategory;
foreach($ItemCategory as $ItemCategorys)
{
echo $ItemCategorys->id;
}
}

Categories