I've tried things like json_combine and array_merge but I can't figure out how to do this.
$query2 = "SELECT DISTINCT cat_id,cat_name FROM review WHERE user_id = ? AND public_or_private = 0";
$stmt2 = $con->prepare($query2) or die(mysqli_error($con));
$stmt2->bind_param('i', $user_id) or die ("MySQLi-stmt binding failed ".$stmt2->error);
$stmt2->execute() or die ("MySQLi-stmt execute failed ".$stmt2->error);
$result2 = $stmt2->get_result();
$array1 = array();
while ($row = mysqli_fetch_assoc($result2)) {
$array1['results'][] = $row;
}
echo json_encode($array1);
The json_encode gives me:
{"results":[{"cat_id":4,"cat_name":"dentist"}]}
And further down in my code I have:
$query3 = "SELECT DISTINCT cat_id,cat_name FROM review WHERE public_or_private = 2";
$result3 = mysqli_query($con,$query3);
$array2 = array();
while($row = mysqli_fetch_assoc($result3)) {
$array2['results'][] = $row;
}
echo json_encode($array2);
The json_encode gives me:
{
"results": [{
"cat_id": "8",
"cat_name": "dental hygienist"
}, {
"cat_id": "5",
"cat_name": "stocktaker"
}, {
"cat_id": "9",
"cat_name": "builder"
}]
}
So in total I have two json arrays:
{
"results": [{
"cat_id": 4,
"cat_name": "dentist"
}]
}
{
"results": [{
"cat_id": "8",
"cat_name": "dental hygienist"
}, {
"cat_id": "5",
"cat_name": "stocktaker"
},
{
"cat_id": "9",
"cat_name": "builder"
}
]
}
But how can I combine these into one like:
{
"results": [{
"cat_id": 4,
"cat_name": "dentist"
}, {
"cat_id": "8",
"cat_name": "dental hygienist"
}, {
"cat_id": "5",
"cat_name": "stocktaker"
},
{
"cat_id": "9",
"cat_name": "builder"
}
]
}
I tried things like:
$jsonArray = array();
foreach (array_combine( $array1, $array2 ) as $name => $value) {
$jsonArray[] = array('cat_id' => $name, 'cat_name' => $value);
}
echo $json = json_encode($jsonArray);
but still couldn't get it to work properly.
I guess you want to use array_merge_recursive instead.
echo json_encode(array_merge_recursive($array1, $array2));
Its not array_combine
You need to merge both array
$array1 = json_decode($array1, true);
$array2 = json_decode($array2, true);
$final_array = array_merge($array1['results'], $array2['results']);
Assuming you already have your arrays, you can do this:
$res1 = [
"results"=> [[
"cat_id"=> 4,
"cat_name"=> "dentist"
]]
];
$res2 = [
"results"=> [[
"cat_id"=> "8",
"cat_name"=> "dental hygienist"
], [
"cat_id"=> "5",
"cat_name"=> "stocktaker"
],
[
"cat_id"=> "9",
"cat_name"=> "builder"
]
]
];
$combinedArray = array_merge_recursive($res1, $res2);
$jsonCombinedArray = json_encode($combinedArray);
This results into
{
"results": [
{"cat_id":4,"cat_name":"dentist"},
{"cat_id":"8","cat_name":"dental hygienist"},
{"cat_id":"5","cat_name":"stocktaker"},
{"cat_id":"9","cat_name":"builder"}
]
}
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 ;)
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
$query = "SELECT id, latitude, longitude, elevation, title, distance, has_detail_webpage, webpage, info FROM korban";
$q=mysql_query($query);
//echo $query;
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
From this code, it will generate like this,
[
{"id":"1","latitude":"-77.036519","longitude":"77.036519","elevation":"0","title":"coba","distance":null,"has_detail_webpage":"0","webpage":"0","info":"0"},
{"id":"3","latitude":"12","longitude":"42","elevation":"21","title":"213","distance":"12","has_detail_webpage":"1","webpage":"12","info":"12"},
{"id":"32","latitude":"","longitude":"","elevation":null,"title":null,"distance":null,"has_detail_webpage":"1","webpage":null,"info":null}
]
But I want something like this,
{ "status": "OK", "num_results": 3, "results":
[ { "id": "2833", "lat": "41.359288", "lng": "-73.646850", "elevation": "53", "title": "Target4", "distance": "1.756", "has_detail_page": "1", "webpage": "" },
{ "id": "2821", "lat": "41.359768", "lng": "-73.646870", "elevation": "0", "title": "Target2", "distance": "1.771", "has_detail_page": "0", "webpage": "" },
{ "id": "2829", "lat": "41.359820", "lng": "-73.646870", "elevation": "0", "title": "Target3", "distance": "1.545", "has_detail_page": "1", "webpage": "" }
] }
How can I do it?
Fetch all your results or do it row by row. Choose yourself. En create the json array afterwards. You also might want to look at your use of mysql_* functions. As they are deprecated now. And you should really switch to MySQli/PDO
$result = array();
while($row = mysql_fetch_assoc($q)) {
$result[] = $row;
}
$output = array('status' => 'OK' , 'num_results' => count($result), 'results' => $result);
echo json_encode($output);
To add the structure you wish to have in your json, first you must create that structure from php before encoding it to json.
$objects = array();
while ($r = mysql_fetch_associ($rs) {
$a = new stdClass();
$a->status = $r['status'];
...
$a->results = array('id' => $r['id']....)
$objects[] = $a;
}
echo json_encode($objects);
$query = "SELECT id, latitude, longitude, elevation, title, distance, has_detail_webpage, webpage, info FROM korban";
$q=mysql_query($query);
$output = array();
if($q) {
$output['status'] = 'OK';
}
$output['num_results'] = mysql_num_rows($q);
while($e=mysql_fetch_assoc($q)) {
$output['results'][]= array (
'id' => $e['id'],
'lat' => $e['latitude'],
'lng' => $e['longitude'],
'elevation' => $e['elevation'],
'title' => $e['title'],
'distance' => $e['distance'],
'has_detail_page' => $e['has_detail_webpage'],
'webpage' => $e['webpage'],
);
}
print(json_encode($output));