create nested json array with php - php

I am newbie to php ,trying to create a nested json array in php but not getting the desired json format.
desired format
{
"offers": [
{
"offerId": "1",
"offerName": "shirts",
"price": "1980",
"storeName": "peter england"
},
{
"offerId": "2",
"offerName": "shirts",
"storeId": "3",
"price": "2970",
"storeName": "peter england"
}
],
"brands": [
{
"brandName": "peter england",
"brandId": "5"
},
{
"brandName": "ruggers",
"brandId": "4"
}
],
"stores": [
{
"storeName": "peter england",
"storeId": "3"
},
{
"storeName": "peter england",
"storeId": "4"
}
],
"filters": [
{
"0": {
"filter": "M",
"filterId": "11"
},
"1": {
"filter": "S",
"filterId": "12"
},
"filterName": "size"
},
{
"0": {
"filter": "red",
"filterId": "13"
},
"1": {
"filter": "blue",
"filterId": "14"
},
"filterName": "colour"
}
]
}
but getting this format
{
"offers": [
{
"offerId": "1",
"offerName": "shirts",
"image": "http://www.offersmashup.com/testing/store/upload/sml_p1.jpg",
"brandId": "5",
"storeId": "3",
"price": "1980",
"offer": "Off-20",
"storeName": "peter england"
},
{
"offerId": "2",
"offerName": "shirts",
"image": "http://www.offersmashup.com/testing/store/upload/sml_p2.jpg",
"brandId": "5",
"storeId": "3",
"price": "2970",
"offer": "Off-30",
"storeName": "peter england"
}
],
"brands": [
{
"brandName": "peter england",
"brandId": "5"
},
{
"brandName": "ruggers",
"brandId": "4"
}
],
"stores": [
{
"storeName": "peter england",
"storeId": "3"
},
{
"storeName": "peter england",
"storeId": "4"
}
],
"filters": {
"0": {
"filter": "M",
"filterId": "11"
},
"1": {
"filter": "S",
"filterId": "12"
},
"filterName": "size"
}
}
my php code is below
$dbFactory = new DBFactory();
$jsonArray = array();
if ($subcatid != '')
{
$p2 = $dbFactory->sel_product3($subcatid, $area_value);
if (count($p2) > 0)
{
for ($j = 0; $j < count($p2); $j++)
{
$p3 = $dbFactory->sel_store($p2[$j]['STORE_ID']);
$temp['offers'][] = array(
"offerId" => $p2[$j]['P_ID'],
"offerName" => $p2[$j]['P_NAME'],
"image" => $url . $p2[$j]['P_ID'] . '.jpg',
"brandId" => $p2[$j]['BRAND_ID'],
"storeId" => $p2[$j]['STORE_ID'],
"price" => $p2[$j]['PRICE'],
"offer" => $p2[$j]['OFFER'],
"storeName" => $p3[0]['S_NAME']
);
$jsonArray = $temp;
}
}
}
// filters code=================
/*code to retrive brnads and stores goes here*/
foreach($res as $value)
{
$br = $dbFactory->sel_brand($value);
$temp["brands"][] = array("brandName" => $br[0]['BRAND_NAME'] ,"brandId"=>$br[0]['BID'] );
$jsonArray = $temp;
}
foreach($store_value as $value)
{
$sr = $dbFactory->sel_store($value);
$temp["stores"][] = array("storeName" => $sr[0][S_NAME] ,"storeId"=>$sr[0][S_ID] );
$jsonArray = $temp;
}
$parentCatId = $dbFactory->getparentcatId($subcatid);
$fg = $dbFactory->get_filtergroup($parentCatId[0]['PARENT_ID']);
for ($i = 0; $i < count($fg); $i++)
{
$f = $dbFactory->sel_filter($fg[$i][F_ID]);
$temp['filters'] = array();
$temp['filters']['filterName'] = $fg[$i][FNAME];
for ($j = 0; $j < count($f); $j++)
{
$temp['filters'][] = array("filter"=>$f[$j][FNAME],"filterId"=>$f[$j][F_ID] );
}
array_push($jsonArray, $temp);
}
$jsonArray = $temp;
echo json_encode($jsonArray);
tried a lot to get the desired json format but failed.please help me out to solve this problem

Related

why object value is repeating in other object, my json reponse is this

foreach ($user_joined_players as $user_joined_player) {
foreach ($batting_live_scores as $batting_live_score) {
if (in_array($batting_live_score['player_id'], explode(',', $user_joined_player['players_id']))) {
$player_data = array();
$player_data['player_id'] = $batting_live_score['player_id'];
$player_data['one'] = $batting_live_score['one'];
$p_data[] = $player_data;
}
}
$user_data['user_name'] = $user_joined_player['fname'];
$user_data['user_players'] = $p_data;
$data[] = $user_data;
}
$json = array("status" => "success", "data" => $data);
{
"status": "success",
"data": [
{
"user_name": "Harshn",
"user_players": [
{
"player_id": "2",
"one": "2"
}
]
},
{
"user_name": "Test",
"user_players": [
{
"player_id": "2",
"one": "2"
},
{
"player_id": "6",
"one": "0"
}
]
},
{
"user_name": "NilSan",
"user_players": [
{
"player_id": "2",
"one": "2"
},
{
"player_id": "6",
"one": "0"
},
{
"player_id": "1",
"one": "1"
}
]
},
{
"user_name": "Raaz",
"user_players": [
{
"player_id": "2",
"one": "2"
},
{
"player_id": "6",
"one": "0"
},
{
"player_id": "1",
"one": "1"
},
{
"player_id": "1",
"one": "1"
}
]
}
]
}
foreach ($batting_live_scores as $batting_live_score) {
if (in_array($batting_live_score['player_id'], explode(',', $user_joined_player['players_id']))) {
$player_data = array();
$player_data['player_id'] = $batting_live_score['player_id'];
$player_data['one'] = $batting_live_score['one'];
$p_data[] = $player_data;
}
}

Group and reformat an array of objects in PHP

I have the following performance problem in PHP code. An external API that I cannot edit, returns a JSON array like this one:
[{"name": "Name 1", "code": "Code 1", "attribute1": "Black", "attribute2": "32", "price": "10"},
{"name": "Name 2", "code": "Code 2", "attribute1": "Yellow", "attribute2": "", "price": "15"},
{"name": "Name 1", "code": "Code 3", "attribute1": "Yellow", "attribute2": "32", "price": "20"},....
]
I want to group this by name and reformat it to a JSON array like this:
[{
"name": "Name 1",
"available_attributes": [ "size", "color" ],
"variations": [
{ "attributes": { "size": "32", "color": "Black" }, "price": "10", "code": "Code 1"},
{ "attributes": { "size": "32", "color": "Yellow" }, "price": "20", "code": "Code 3"}
]
}, {
"name": "Name 2",
"available_attributes": [ "color" ],
"variations": [ { "attributes": { "color": "Yellow" }, "price": "15", "code": "Code 2"}]
}]
My solution is ugly and time-consuming since I used a simple brute force to iterate on the response and then again every time on the array to update the one I have already there.
So, I am looking for a solution focused on performance and speed.
Edit. This is my code. The only difference is that in case of both attributes being empty, instead of the variations and available_attributes arrays, it has the price and the sku only.
function cmp( $a, $b ) {
if ( $a['name'] == $b['name'] ) {
return 0;
}
return ( $a['name'] < $b['name'] ) ? - 1 : 1;
}
function format_products_array($products) {
usort( $products, "cmp" );
$formatted_products = array();
$new = true;
$obj = array();
for ( $i = 0; $i < count( $products ); $i++ ) {
if ( $new ) {
$obj = array();
$attr = array();
$obj['available_attributes'] = array();
$obj['variations'] = array();
$obj['name'] = $products[$i]['name'];
if ( $products[$i]['attribute1'] != '' ) {
array_push( $obj['available_attributes'], 'color' );
$attr['color'] = $products[$i]['attribute1'];
}
if ( $products[$i]['attribute2'] != '' ) {
array_push( $obj['available_attributes'], 'size' );
$attr['size'] = $products[$i]['attribute2'];
}
}
if ( $products[ $i ]['name'] == $products[ $i + 1 ]['name']) {
$new = false;
$attr['size'] = $products[$i]['attribute2'];
$attr['color'] = $products[$i]['attribute1'];
if ( empty($obj['available_attributes']) ) {
$obj['price'] = $products[$i]['price'];
} else {
$var = array();
$var['price'] = $products[$i]['price'];
$var['code'] = $products[$i]['code'];
$var['attributes'] = $attr;
array_push($obj['variations'], $var);
}
} else {
$new = true;
if ( empty($obj['available_attributes']) ) {
$obj['price'] = $products[$i]['price'];
}
$attr['size'] = $products[$i]['attribute2'];
$attr['color'] = $products[$i]['attribute1'];
$var['attributes'] = $attr;
array_push($obj['variations'], $var);
array_push($formatted_products, $obj);
}
}
return $formatted_products;
}
A faster solution is when generating the array to store the unique identifies or each object eg to generate:
[
"Name1":{
"name": "Name 1",
"code": "Code 1",
"available_attributes": [ "size", "color" ],
"variations": [
{ "attributes": { "size": "32", "color": "Black" }, "price": "10"},
{ "attributes": { "size": "32", "color": "Yellow" }, "price": "20"}
]
},
"Name2": {
"name": "Name 2",
"code": "Code 2",
"available_attributes": [ "color" ],
"variations": [ { "attributes": { "color": "Yellow" }, "price": "15"}]
}]
OR
[
"Code 1":{
"name": "Name 1",
"code": "Code 1",
"available_attributes": [ "size", "color" ],
"variations": [
{ "attributes": { "size": "32", "color": "Black" }, "price": "10"},
{ "attributes": { "size": "32", "color": "Yellow" }, "price": "20"}
]
},
"Code 2": {
"name": "Name 2",
"code": "Code 2",
"available_attributes": [ "color" ],
"variations": [ { "attributes": { "color": "Yellow" }, "price": "15"}]
}]
Afterwards (optionally)remove any association.
Afterwards you may store them in a memcached/redis then when you need to re-retrieve the same data then just look in redis/memcached first.
So it may be time consuming at first but afterwards it will be ready to do that so they will be only on "unlucky" guy/girl who will do the very same thing.
In case it is extreemely time consuming loops then use a worker to generate theese data ans store them in an document-based storage such as mongodb/couchdb afterwards the site will look on the ready made document.

php multidimensional array json encode valid output

icant figure it out how to encode a valid json from my array
tried every posible way to encode json i had no luck
thankyou for your time
<?php
// this array is very large i used small piece as example
$listarray = array(
array(87,108,173,0,0),
array(87,108,173,0,1),
array(87,108,173,0,2),
array(87,108,173,0,3),
array(87,108,173,0,4),
array(87,108,173,0,5),
array(79,99,163,0,6),
array(79,99,163,0,7),
array(79,99,163,0,8),
array(79,99,163,0,9),
array(92,97,158,0,10),
array(92,97,158,0,11),
array(76,91,153,0,12),
array(79,99,163,0,13),
array(76,91,153,0,14),
array(92,97,158,0,15),
array(76,91,153,0,16),
array(76,91,153,0,17),
array(133,157,215,1,47),
array(133,157,215,1,48),
array(133,157,215,1,49),
array(133,157,215,1,50),
array(133,157,215,1,51),
array(133,157,215,1,52),
array(133,157,215,1,53),
array(143,168,222,1,54),
array(156,180,227,1,55),
array(156,180,227,1,56),
array(142,175,243,1,57),
array(156,180,227,1,58),
array(156,180,227,1,59),
array(156,180,227,1,60),
array(133,157,215,1,61));
for ($key = 0, $size = count($listarray); $key < $size; $key++) {
$array = array_values($listarray[$key]);
$line = $array[3]+1; //+1 start counting from 1
$loc = $array[4]+1; //+1 start counting from 1
$Name = $array[0].'_'.$array[1].'_'.$array[2];
$data = new StdClass();
$data->$line->$Name = array("$loc",);
$json = json_encode($data,JSON_PRETTY_PRINT);
echo $json."<br>";
//// echo give somthing like this and it is unusable for me
//{ "1": { "87_108_173": [ "1" ] } }
//{ "1": { "87_108_173": [ "2" ] } }
//{ "1": { "87_108_173": [ "3" ] } }
//{ "1": { "87_108_173": [ "4" ] } }
//{ "1": { "87_108_173": [ "5" ] } }
//{ "1": { "87_108_173": [ "6" ] } }
////
$fh = fopen("jsonout.json", 'w')or die("Error opening output file");
fwrite($fh, json_encode($data,JSON_PRETTY_PRINT));
fclose($fh);
}// end of for loop
?>
// and contents of jsonout.json is not valid
//the out put needed as shoud be exactly like this
// json blew is manualy made with app and validated
{
"1": {
"87_108_173": [
"1",
"2",
"3",
"4",
"5",
"6"
],
"92_97_158": [
"11",
"12",
"16"
],
"79_99_163": [
"7",
"8",
"9",
"14"
],
"76_91_153": [
"13",
"15",
"17",
"18"
]
},
"2": {
"156_180_227": [
"56",
"57",
"59",
"60",
"61"
],
"142_175_243": [
"58"
],
"133_157_215": [
"48",
"49",
"50",
"51",
"52",
"53",
"54",
"62"
],
"143_168_222": [
"55"
]
}
}
$listarray = array(
array(87,108,173,0,0),
array(87,108,173,0,1),
array(87,108,173,0,2),
array(87,108,173,0,3),
array(133,157,215,1,47),
array(133,157,215,1,48),
array(133,157,215,1,49),
array(133,157,215,1,50),
array(133,157,215,1,51),
array(133,157,215,1,52),
);
$resultArray = array();
foreach ($listarray as $row) {
$ind = $row[3] + 1;
$name = $row[0] . '_' . $row[1] . '_' . $row[2];
$val = $row[4] + 1;
if (!isset($resultArray[$ind])) {
$resultArray[$ind] = array();
}
if (!isset($resultArray[$ind][$name])) {
$resultArray[$ind][$name] = array();
}
$resultArray[$ind][$name][] = $val;
}
echo json_encode($resultArray, JSON_PRETTY_PRINT);
You are welcome ;)

Parsing an array 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.
[
{
"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"
},
{
"name": "select-deopdown",
"value": ""
},
{
"name": "true",
"value": "false"
},
{
"name": "number",
"value": "55"
}
]
}
]
I want to separate the value 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);
}

How to merge JSON two indexes and then Parse information

I am trying to iterate both index of JSON(Players and Buildings), so that i can a get new result in jQuery
I have two index of JSON one having information of Players and second index having information of Building related Player.
I want to Parse it so that i can get Player and its building name.
My Actual JSON result
{
"Players": [
{
"id": "35",
"building_id": "8",
"room_num": "101",
},
{
"id": "36",
"building_id": "9",
"room_num": "102",
},
{
"id": "37",
"building_id": "10",
"room_num": "103",
},
{
"id": "38",
"building_id": "11",
"room_num": "104",
}
],
"Buildings": [
{
"id": "8",
"name": "ABC"
},
{
"id": "9",
"name": "DEF"
},
{
"id": "10",
"name": "GHI"
},
{
"id": "11",
"name": "JKL"
}
]
}
Need this
"information": [
{
"player_id": "35",
"Buildings_name": "ABC"
},
{
"player_id": "36",
"Buildings_name": "DEF"
},
{
"player_id": "37",
"Buildings_name": "GHI"
},
{
"player_id": "38",
"Buildings_name": "JKL"
}
]
}
Here you go, this go for each player and check if there are buildings and will map them to new structure. This will not filter values for buildings that do not have mapping to players, and will not include the buildings with no players.
var x = {
"Players": [
{
"id": "35",
"building_id": "8",
"room_num": "101",
},
{
"id": "36",
"building_id": "9",
"room_num": "102",
},
{
"id": "37",
"building_id": "10",
"room_num": "103",
},
{
"id": "38",
"building_id": "11",
"room_num": "104",
}
],
"Buildings": [
{
"id": "8",
"name": "ABC"
},
{
"id": "9",
"name": "DEF"
},
{
"id": "10",
"name": "GHI"
},
{
"id": "11",
"name": "JKL"
}
]
};
var res = $.map(x.Players, function(item) {
return {
player_id: item.id,
building_name: $.grep(x.Buildings, function(i) {
return i.id == item.building_id
}).length != 0 ? $.grep(x.Buildings, function(i) {
return i.id == item.building_id
})[0].name : undefined
}
})
and if you want to filter values that do not have relationships e.g INNER join
var resInnerJoin = $.grep($.map(x.Players, function(item) {
return {
player_id: item.id,
building_name: $.grep(x.Buildings, function(i) {
return i.id == item.building_id
}).length != 0 ? $.grep(x.Buildings, function(i) {
return i.id == item.building_id
})[0].name : undefined
}
}), function(it) {
return it.building_name != undefined
})
If you need it in PHP :
$json = '{...}';
// create and PHP array with you json data.
$array = json_decode($json, true);
// make an array with buildings informations and with building id as key
$buildings = array();
foreach( $array['Buildings'] as $b ) $buildings[$b['id']] = $b;
$informations = array();
for ( $i = 0 ; $i < count($array['Players']) ; $i++ )
{
$informations[$i] = array(
'player_id' => $array['Players'][$i]['id'],
'Buildings_name' => $buildings[$array['Players'][$i]['building_id']]['name']
);
}
$informations = json_encode($informations);
var_dump($informations);

Categories