create tree view like json from existing combined array - php

I have one combined array of order and its items combined into one array but i am trying to create json structure like order then its items list like wise.
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'abc',"price"=>250);
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'xyz',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'pqr',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'lmn',"price"=>250);
Output should be like
[
"0":[
{
"OrderNo": "1",
"partycode": "10",
"OrderDetails": [
{
"Item": "abc",
"price": 250
},
{
"Item": "xyz",
"price": 250
}
]
}
],
"1":[
{
"OrderNo": "2",
"partycode": "20",
"OrderDetails": [
{
"Item": "pqr",
"price": 250
},
{
"Item": "lmn",
"price": 250
}
]
}
]
]
This is What i Tried
$mainarray = array();
$orderarray = array();
$orderitemarray = array();
if (count(combinedarray) > 0) {
foreach (combinedarray as $obj) {
$orderarray[] = array("orderid" => $obj->orderid);
$orderitemarray[] = array("Item" => $obj->Item, "price" => $obj->price);
}
}
$mainarray[] = array_unique($orderarray);
$mainarray['OrderDetails'] = $orderitemarray;
echo json_encode($mainarray);

$mainarray = array();
foreach ($combinedarray as $x) {
$id = $x['orderid'];
unset($x['orderid']);
if (! isset($mainarray[$id])) {
$mainarray[$id]['OrderNo'] = $id;
}
$mainarray[$id]["OrderDetails"][] = $x;
}
// Now $mainarray has indexes equal to OrderNo. To count it from zero, use array_values
echo json_encode(array_values($mainarray), JSON_PRETTY_PRINT);
demo

By your given array
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'abc',"price"=>250);
$combinedarray[]=array('orderid'=>1,'partycode'=>10,"item"=>'xyz',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'pqr',"price"=>250);
$combinedarray[]=array('orderid'=>2,'partycode'=>20,"item"=>'lmn',"price"=>250);
Here is my solution for this
$new = array();
foreach($combinedarray as $r){
$new[$r['orderid']]['orderid'] = $r['orderid'];
$new[$r['orderid']]['partycode'] = $r['partycode'];
$new[$r['orderid']][] = array("item"=>$r['item'],"price"=>$r['price']);
}
$json = json_encode($new);
echo '<pre>';print_r($new);
echo $json;

Related

Export database to json in a specific format

When Exporting database to json I get it in this form:
[
{
"id": "1",
"siteId": "1",
"siteUrl": "localhost",
"identity": "mobie",
"lastIp": "127.0.0.1",
"lastLogin": "2018-05-17",
"loginCountry": "GB",
}
]
Warning: Illegal string offset 'id' in C:\xamppp\htdocs\auth\mysql.php on line 81
To all of the $user variables.
My database structure is shown as above in the first json output.
Code
public function db2json($query){
$stmt = $this->db->prepare($query);
$stmt->execute();
$data=$stmt->fetch(PDO::FETCH_ASSOC);
$output = [];
foreach ( $data as $result ) { // Change this to loop over the data
$user = [];
$user["id"] = $result["id"];
$user["siteId"] = $result["siteId"];
$user["lastIp"] = $result["lastIp"];
$user["lastLogin"] = $result["lastLogin"];
$user["loginCountry"] = $result["loginCountry"];
$output[$result["siteUrl"]][$result["identity"]] = $user;
}
echo json_encode($output, JSON_PRETTY_PRINT);
}
I have had to build up some test data, but this will just mean that you change the foreach() to loop over your database result instead. Rather than just assigning the result straight to the output, this just creates the various arrays as you want them in the output...
$output = [];
foreach ( $data as $result ) { // Change this to loop over the data
$user = [];
$user["id"] = $result["id"];
$user["siteId"] = $result["siteId"];
$user["lastIp"] = $result["lastIp"];
$user["lastLogin"] = $result["lastLogin"];
$user["loginCountry"] = $result["loginCountry"];
$output[$result["siteUrl"]][$result["identity"]] = $user;
}
echo json_encode($output, JSON_PRETTY_PRINT);
With my test data, this outputs...
{
"localhost": {
"mobie": {
"id": "1",
"siteId": "1",
"lastIp": "127.0.0.1",
"lastLogin": "2018-05-17",
"loginCountry": "GB"
},
"user2": {
"id": "1",
"siteId": "1",
"lastIp": "127.0.0.1",
"lastLogin": "2018-05-17",
"loginCountry": "GB"
}
},
"othersite": {
"user1": {
"id": "1",
"siteId": "1",
"lastIp": "127.0.0.1",
"lastLogin": "2018-05-17",
"loginCountry": "GB"
}
}
}

How to merge MySQL query result with JSON format

Hi i am trying to merge output of MySQL result in JSON format but i confused how i can do this so guys i need your helps please tell me how i can do this work thank you.
SQL:
$result = $db->sql_query("SELECT a.*,i.member_id,i.members_seo_name
FROM ".TBL_IPB_USER." i
LEFT JOIN ".TBL_IPB_LA." a
ON a.member_id=i.member_id
WHERE i.".$column." = '".$val."' AND a.game = '".$game."'");
while( $dbarray = $db->sql_fetchrow($result) ){
$arr[] = $dbarray;
}
return ($arr);
The normal result and output with JSON format for my query is:
{
"status": 200,
"result": [
{
"member_id": "1",
"member_name": "maxdom",
"ip_address": "177.68.246.162",
"session_onlineplay": "1",
"sid": "IR63374a32d1424b9288c5f2a5ce161d",
"xuid": "0110000100000001",
"serialnumber": "9923806a06b7f700a6ef607099cb71c6",
"game": "PlusMW3",
"members_seo_name": "maxdom"
},
{
"member_id": "1",
"member_name": "maxdom",
"ip_address": "81.254.186.210",
"session_onlineplay": "1",
"sid": "IR3cd62da2f143e7b5c8f652d32ed314",
"xuid": "0110000100000001",
"serialnumber": "978e2b2668ec26e77c40c760f89c7b31",
"game": "PlusMW3",
"members_seo_name": "maxdom"
}
],
"handle": "checkUSER"
}
But i want to merge output and result like this one:
{
"status": 200,
"result": [
{
"member_id": "1",
"member_name": "maxdom",
"ip_address": [
"177.68.246.162",
"81.254.186.210"
],
"session_onlineplay": "1",
"sid": [
"IR63374a32d1424b9288c5f2a5ce161d",
"IR3cd62da2f143e7b5c8f652d32ed314"
],
"xuid": "0110000100000001",
"serialnumber": [
"9923806a06b7f700a6ef607099cb71c6",
"978e2b2668ec26e77c40c760f89c7b31"
],
"game": "PlusMW3",
"members_seo_name": "maxdom"
}
],
"handle": "checkUSER"
}
you better use php for your parser, prevent high load for database, this is sample code
$result = $db->sql_query("SELECT a.*,i.member_id,i.members_seo_name
FROM ".TBL_IPB_USER." i
LEFT JOIN ".TBL_IPB_LA." a
ON a.member_id=i.member_id
WHERE i.".$column." = '".$val."' AND a.game = '".$game."'");
$arr = array();
while( $dbarray = $db->sql_fetchrow($result) ){
$item = $dbarray;
$item['ip_address'] = array($item['ip_address']);
$item['sid'] = array($item['sid']);
$item['serialnumber'] = array($item['serialnumber']);
$index = $dbarray['member_id'];
if(isset($arr[$index]))
{
$arr[$index]['ip_address'] = array_merge($arr[$index]['ip_address'], $item['ip_address'];
$arr[$index]['sid'] = array_merge($arr[$index]['sid'], $item['sid'];
$arr[$index]['serialnumber'] = array_merge($arr[$index]['serialnumber'], $item['serialnumber']);
} else {
$arr[$index] = $item;
}
}
return array_values($arr);

merge arrays with same value of key

I use php glob function for get images in sub directories and I dont know how many files exist in each directory
directory name is id and I want to categorize all images in directories in one array
$arr = [];
$dir = dirname(__FILE__)."/gulets";
$files = glob($dir."/*/*_gulet_o_*");
foreach ($files as $file) {
$fullname = str_replace($dir."/", "", $file);
$name = explode("/", $fullname);
$name1 = array('id'=>$name[0],'name'=>$name[1]);
$arr[] = $name1;
}
header('Content-Type: application/json');
echo json_encode($arr);
[
{
"id": "10",
"name": "asdsad_gulet_o_1.jpg"
},
{
"id": "10",
"name": "wqes_gulet_o_10.jpg"
},
{
"id": "10",
"name": "qwsdf_gulet_o_11.jpg"
},
{
"id": "10",
"name": "sdce_gulet_o_12.jpg"
},
{
"id": "11",
"name": "fsdsc_gulet_o_13.jpg"
},
{
"id": "11",
"name": "drfvc_gulet_o_14.jpg"
},
{
"id": "12",
"name": "dsyjhk_gulet_o_15.jpg"
},
.
.
and I need change it like this :
[
{
"id": "10",
"name1": "asdsad_gulet_o_1.jpg",
"name2": "wqes_gulet_o_10.jpg",
"name3": "qwsdf_gulet_o_11.jpg"
"name4": "sdce_gulet_o_12.jpg"
},
{
"id": "11",
"name1": "fsdsc_gulet_o_13.jpg"
"name2": "drfvc_gulet_o_14.jpg"
},
{
"id": "12",
"name1": "dsyjhk_gulet_o_15.jpg"
.
.
you want something like this:
foreach ($arr as $a) {
$new_arr[$a['id']]['names'][] = $a['name'];
}
I think creating indexes like name1, name2, name3 etc is not useful. You should create subarray with index names and there put your names. Try code like this:
<?php
$array = array(
array('id'=>1, 'name'=>'qwerty'),
array('id'=>2, 'name'=>'asdf'),
array('id'=>2, 'name'=>'hjkl'),
array('id'=>1, 'name'=>'cvbnm'),
array('id'=>1, 'name'=>'yuiop'),
);
$groups = array();
foreach($array as $singleRow)
{
if(!isset($groups[$singleRow['id']]))
$groups[$singleRow['id']] = array('id'=>$singleRow['id'], 'names'=>array());
$groups[$singleRow['id']]['names'][] = $singleRow['name'];
}
$json = json_encode(array_values($groups));
var_dump($json);
It outputs:
[{"id":1,"names":["qwerty","cvbnm","yuiop"]},{"id":2,"names":["asdf","hjkl"]}]
instead of -
$name1 = array('id'=>$name[0],'name'=>$name[1]);
$arr[] = $name1;
you can use something like -
$nameKey = 'name' . $name[0];
$name1 = array('id'=>$name[0],$nameKey =>$name[1]);
if (!empty($arr[$name[0]])) {
$arr[$name[0]] = $arr[$name[0]] + $name1;
}
else {
$arr[$name[0]] = $name1;
}
and after end of foreach() loop do -
$arr = array_values($arr);

Parsing array value with PHP in a foreach loop

I want to parse an array with PHP's foreach loop to get the object names and values inside the 'ques' array.I want
[
{
"ques": [
{
"name": "comment",
"value": "comment me for the reason",
"sur_id": "1",
"user_id": "admin#gmail.com",
"pagename": "question_response"
},
{
"name": "check-box[]",
"value": "1"
},
{
"name": "radio",
"value": "radio 2"
},
{
"name": "yes",
"value": "no"
}
]
"ques":[
{
"name": "date",
"value": "2015-10-23"
"user_id": "admin1#gmail.com",
},
{
"name": "select-deopdown",
"value": ""
},
{
"name": "true",
"value": "false"
},
{
"name": "number",
"value": "55"
}
]
}
]
I want to separate the name,value and user_id from the 'ques' array:
while ($fetch = mysql_fetch_array($query1)) {
$content = $fetch['CONTENT_VALUES'];
// print_r($content);
$content_value= mb_convert_encoding($content ,"UTF-8");
$datas = json_decode($content, true);
foreach($datas->ques as $values)
{
echo $values->value . "\n";
print_r($values);
}
$test[] = array('ques' => $datas ,'answer'=>$values);
}
If you want to make three different array for each value then create three blank array and then storing corresponding values into them in foreach . Am giving you a common example below
$name = array();
$values= array();
$users = array();
foreach($datas->ques as $values) {
$name[] = $values->name;
$values[] = $values->value;
$users[] = !empty($values->user_id) ? $values->user_id : '';
}
and further you can modify according your need.
Thank you.
This could help
$data = json_decode($json);
$result = [];
foreach($data as $row)
{
foreach($row as $k => $v)
{
$i = 0;
foreach($v as $key => $val)
{
foreach($val as $k1 => $v1)
{
$result[$i][$k1] = $v1;
}
$i++;
}
}
}
echo json_encode($result);
foreach($datas->ques as $values)
{
$name = $values['name'];
$value = $values['value'];
$user_id = $values['user_id'];
}
I solved this by following code.Thanks for 3 of them to guide by giving ideas.
$datas = json_decode($content, true);
foreach($datas as $values)
{
$name = $values['name'];
$value = $values['value'];
$user_id = $values['user_id'];
$test[]= array('user'=>$user,'name'=>$name,'value'=>$value);
}
}

JSON Output Array

I'm attempting to output my JSON in a format just like this: http://api.androidhive.info/json/movies.json and I am unsure of how to accomplish this through my PHP output code. Right now, It is displaying with "post" at the top and is a map, which I don't know how to successfully remove, seen here: http://shipstudent.com/complaint_desk/androidfriendsList.php?username=noah. Please let me know if you need more information.
PHP:
$rows = $stmt->fetchAll();
if ($rows) {
$response["posts"] = array();
foreach ($rows as $row)
{
$post = array();
$post["username"] = $row["username"];
$post["profile_picture"] = $row["profile_picture"];
array_push($response["posts"], $post);
}
// echoing JSON response
echo json_encode($response);
} else
{
die(json_encode($response));
}
JSON:
{
"posts": [
{
"username": "noah",
"profile_picture": "https://shipstudent.com/animal/appphotos/978321177.jpg"
},
{
"username": "e",
"profile_picture": "https://shipstudent.com/complaint_desk/appphotos/owl.jpeg"
},
]
}
Desired format:
[{
"title": "Dawn of the Planet of the Apes",
"image": "http://api.androidhive.info/json/movies/1.jpg",
"rating": 8.3,
"releaseYear": 2014,
"genre": ["Action", "Drama", "Sci-Fi"]
},
{
"title": "District 9",
"image": "http://api.androidhive.info/json/movies/2.jpg",
"rating": 8,
"releaseYear": 2009,
"genre": ["Action", "Sci-Fi", "Thriller"]
},
$rows = $stmt->fetchAll();
$response = [];
foreach ($rows as $row) {
$post = [
"username" => $row["username"],
"profile_picture" => $row["profile_picture"]
];
$response[] = $post;
}
echo json_encode($response);
$response = array();
foreach ($rows as $row)
{
$post = array();
$post["title"] => // define title;
$post["image"] => // define image;
$post["rating"] => // define rating;
$post["releaseYear"] => // define releaseYear;
$post["genre"] => // define genre, must be array();
array_push($response, $post);
}

Categories