I have fetch value from database and returning its array in json format. This is my code to get values. First array is working fine. But i need to add static array after every index in array. This is my code
$value = $this->TestModel->get_user_details($userIds);
this function returns array in json format e.g.
[
{
"user_id": "1",
"name": "test 1",
},
{
"user_id": "2",
"name": "test 2",
},
{
"user_id": "3",
"name": "test 3",
},
]
now i need to add below static json array with every item of array. This is e.g
$test1= array("student_list"=> array(array("stu_id"=>1, "name"=> "abc") , array("stu_id"=>2, "name"=> "xyz")),
"class"=> "12th",
"average_score"=>"5",
"results"=>array(array("result_date"=>"2012-12-13","city"=>"city 1"),array("result_date"=>"2015-10-13","city"=>"city 2")));
I have tried it with array_push and array_merge but it add this at the end end of array.
I need this Response
[
{
"user_id": "1",
"name": "test 1",
"student_list": [
{
"stu_id": 1,
"name": "abc",
},
{
"stu_id": 2,
"name": "xyz",
}
],
"class": "12th",
"average_score": "5",
"results": [
{
"result_date": "2012-12-13",
"city": "City 1",
},
{
"result_date": "2012-10-13",
"city": "City 2",
}
]
},
{
"user_id": "2",
"name": "test 2",
"student_list": [
{
"stu_id": 3,
"name": "asd",
},
{
"stu_id": 4,
"name": "ghj",
}
],
"class": "10th",
"average_score": "5",
"results": [
{
"result_date": "2011-12-13",
"city": "City 3",
},
{
"result_date": "2011-10-13",
"city": "City 4",
}
]
},
]
If you want to add $test1 to to every element you your array you should merge each element, like so:
$value = $this->TestModel->get_user_details($userIds);
$test1 = array(
"student_list" => array(array("stu_id" => 1, "name" => "abc"), array("stu_id" => 2, "name" => "xyz")),
"class" => "12th",
"average_score" => "5",
"results" => array(array("result_date" => "2012-12-13", "city" => "city 1"), array("result_date" => "2015-10-13", "city" => "city 2"))
);
$decoded = json_decode($value, true);
for ($i = 0; $i < count($decoded); $i++) {
$decoded[$i] = array_merge($decoded[$i], $test1);
}
$value = json_encode($decoded);
Related
I have mysqli query that I fetch and the code below turns results into array, but I get unwanted dynamic keys 1 ,2, 3 etc. my question is it possible to remove them or do it somehow differently?
if($num > 0) {
$quest_arr['error'] = 'false';
$quest_arr['message'] = 'Success';
$quest_arr['data'] = array();
$questions = [];
foreach ($result as $r) {
if (!isset($questions[$r['QuestionId']])) {
$questions[$r['QuestionId']] = [ 'QuestionId' => $r['QuestionId'],
'question' => $r['QuestionName'],
'answers'=> []
];
}
$questions[$r['QuestionId']]['answers'][] = $r['AnswerID'];
}
array_push($quest_arr['data'], $questions);
echo json_encode($quest_arr, JSON_NUMERIC_CHECK);
} else {
echo json_encode(
array('error' => 'true','message' => 'Error')
);
}
Creates this array
{
"error": "false",
"message": "Success",
"data": [
{
"1": {
"QuestionId": 1,
"question": "Question 1",
"answers": [
1,
2,
3
]
},
"2": {
"QuestionId": 2,
"question": "Question 2",
"answers": [
null
]
},
"3": {
"QuestionId": 3,
"question": "Question 3",
"answers": [
null
]
},
}
]
}
Is it possible to remove the dynamic keys "1", "2" ,"3" ?
I would love to have json like this
{
"error": "false",
"message": "Success",
"data": [
{
"QuestionId": 1,
"question": "Question 1",
"answers": [
1,
2,
3
]
},
{
"QuestionId": 2,
"question": "Question 2",
"answers": [
null
]
},
{
"QuestionId": 3,
"question": "Question 3",
"answers": [
null
]
},
]
}
Not tested, but maybe this can work:
// instead of
// array_push($quest_arr['data'], $questions);
$questions = array_values($questions);
$quest_arr['data'] = $questions;
I have an SQL Query returning certain fields, I am using json_encode() to get the data in JSON format, however I am having trouble getting it in the format I want.
PHP Code
<?php
function data() {
$runDistanceBasedOnCityQuery = "SELECT rc.id, rc.cityId, c.cityName, rc.runId, r.distance, rc.status FROM run_city rc INNER JOIN cities c ON c.id = rc.cityId INNER JOIN run_distance r ON r.id = rc.runId ORDER BY c.cityName";
$runDistanceBasedOnCityResult = $db->prepare($runDistanceBasedOnCityQuery);
$runDistanceBasedOnCityResult->bindParam(":cityId", $cityId, PDO::PARAM_INT);
$runDistanceBasedOnCityResult->execute();
$runDistanceBasedOnCityOutput = $runDistanceBasedOnCityResult->rowCount();
if ($runDistanceBasedOnCityOutput > 0) {
while ($runDistanceBasedOnCityRow = $runDistanceBasedOnCityResult->fetch(PDO::FETCH_ASSOC)) {
$array1 = array($runDistanceBasedOnCityRow['runId'], $runDistanceBasedOnCityRow['distance'], $runDistanceBasedOnCityRow['status']);
for ($i = 0; $i < sizeof($array1); $i++) {
$array2 = array("id" => $runDistanceBasedOnCityRow['id'], "runId" => $runDistanceBasedOnCityRow['cityId'], $runDistanceBasedOnCityRow['cityName'] => $array1);
}
$finalResultRunDistanceBasedOnCity[] = $array2;
}
$responseRunDistanceBasedOnCity = $finalResultRunDistanceBasedOnCity;
} else {
$responseRunDistanceBasedOnCity = 'Runs not found';
}
$result = array("status" => true,
"runsBasedOnCity" => $responseRunDistanceBasedOnCity
);
json($result);
}
function json($data) {
header('Content-Type:application/json');
if (is_array($data)) {
echo json_encode($data);
}
}
?>
The JSON format I am getting
"runsBasedOnCity": [
{
"id": "1",
"runId": "1",
"Bengaluru": [
"2",
"10k",
"1"
]
},
{
"id": "2",
"runId": "1",
"Bengaluru": [
"1",
"5k",
"1"
]
},
{
"id": "3",
"runId": "1",
"Bengaluru": [
"5",
"3k",
"0"
]
},
{
"id": "4",
"runId": "2",
"Chennai": [
"1",
"5k",
"1"
]
},
{
"id": "5",
"runId": "2",
"Chennai": [
"2",
"10k",
"1"
]
},
{
"id": "6",
"runId": "2",
"Chennai": [
"4",
"15k",
"1"
]
}
]
The Format I Require
"runsBasedOnCity": [
{
"id": "1",
"cityId": "1",
"Bengaluru":
[
{
runId : "2",
distance : "10k",
status : "1"
},
{
runId : "1",
distance: "5k",
status : "1"
},
{
runId : "5",
distance : "3k",
status : "0"
}
]
},
{
"id": "2",
"cityId": "2",
"Chennai":
[
{
runId : "1",
distance : "5k",
status : "1"
},
{
runId : "2",
distance: "10k",
status : "1"
},
{
runId : "4",
distance : "15k",
status : "1"
}
]
}
I am not able to figure out a better way of doing this, I am fairly new to this, do help me out. Thanks !
To efficiently group the subarray data, you should implement temporary keys. cityId is a suitable value to group by -- because cityNames may intentionally duplicate in the future but cityId must never un/intentionally duplicate in your database table.
When each new cityId is encountered, the conditional isset() call will determine whether a new/full set of data should be stored, or if data should merely be appended to the subarray.
I am calling array_slice() since it cuts down on unnecessary syntax / code-bloat.
After iterating through all of the rows, you can reindex the $result array, nest it inside runBasedOnCity, and add the status element.
I'll show my demo with PRETTY_PRINT so that it is easier to read, but in your actual code, you should remove the parameter. Also, a word of advice -- try to keep your variable names brief for improved readability.
Code: (Demo)
$resultset = [
["id" => "1", "cityId" => "1", "cityName" => "Bengaluru", "runId" => "2", "distance" => "10k", "status" => "1"],
["id" => "2", "cityId" => "1", "cityName" => "Bengaluru", "runId" => "1", "distance" => "5k", "status" => "1"],
["id" => "3", "cityId" => "1", "cityName" => "Bengaluru", "runId" => "5", "distance" => "3k", "status" => "0"],
["id" => "4", "cityId" => "2", "cityName" => "Chennai", "runId" => "1", "distance" => "5k", "status" => "1"],
["id" => "5", "cityId" => "2", "cityName" => "Chennai", "runId" => "2", "distance" => "10k", "status" => "1"],
["id" => "6", "cityId" => "2", "cityName" => "Chennai", "runId" => "4", "distance" => "15k", "status" => "1"]
];
foreach ($resultset as $row) {
if (!isset($result[$row["cityId"]])) {
$result[$row["cityId"]] = array("id" => $row["id"], "cityId" => $row["cityId"], $row["cityName"] => array(array_slice($row,-3)));
} else {
$result[$row['cityId']][$row["cityName"]][] = array_slice($row,-3);
}
}
if (!isset($result)) { // don't need to check rowCount() at all
$result = 'Runs not found';
} else {
$result = array_values($result);
}
$result = array("status" => true, "runsBasedOnCity" => $result);
var_export(json_encode($result, JSON_PRETTY_PRINT));
Output:
'{
"status": true,
"runsBasedOnCity": [
{
"id": "1",
"cityId": "1",
"Bengaluru": [
{
"runId": "2",
"distance": "10k",
"status": "1"
},
{
"runId": "1",
"distance": "5k",
"status": "1"
},
{
"runId": "5",
"distance": "3k",
"status": "0"
}
]
},
{
"id": "4",
"cityId": "2",
"Chennai": [
{
"runId": "1",
"distance": "5k",
"status": "1"
},
{
"runId": "2",
"distance": "10k",
"status": "1"
},
{
"runId": "4",
"distance": "15k",
"status": "1"
}
]
}
]
}'
After explaining how you wanted to preserve the id values in the subarrays, here is that solution:
Code: (Demo)
foreach ($resultset as $row) {
if (!isset($result[$row["cityId"]])) {
$result[$row["cityId"]] = array("cityId" => $row["cityId"], $row["cityName"] => array(array("id" => $row["id"])+array_slice($row,-3)));
} else {
$result[$row['cityId']][$row["cityName"]][] = array("id" => $row["id"])+array_slice($row,-3);
}
}
if (!isset($result)) { // don't need to check rowCount() at all
$result = 'Runs not found';
} else {
$result = array_values($result);
}
$result = array("status" => true, "runsBasedOnCity" => $result);
var_export(json_encode($result, JSON_PRETTY_PRINT));
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.
I want JSON object as follows in that personal, address and itm have sequence of json object.
{
"id": "1",
"state": "12",
"personal": [
{
"name": "abc",
"contact":"1111111"
"address": [
{
"line1": "abc",
"city": "abc",
"itm": [
{
"num": 1,
"itm_detatils": {
"itemname": "bag",
"rate": 1000,
"discount": 0,
}
}
],
"status": "Y"
}
]
}
]
}
But I am getting result as follows in that I want json array at address and itm_details.
{
"id": "1",
"state": "12",
"personal": [
{
"name": "abc",
"contact": "1111111",
"address": {
"line1": "abc",
"city": "abc",
"itm": {
"inum": "1",
"itm_detatils": {
"itemname": "bag",
"rate": 1000,
"discount": 0
}
},
"status": "Y"
}
}
]
}
My PHP Code is as follow:
In that I am creating simple array and after that array inside array but during encoding to json it's not showing sequence of json object.
$a=array();
$a["id"]="1";
$a["state"]="12";
$a["personal"]=array();
$a["personal"][]=array(
"name"=>"abc",
"contact"=>"1111111",
"address"=>array(
"line1"=>"abc",
"city"=>"abc",
"itm"=>array(
"inum"=>"1",
"itm_detatils"=>array(
"itemname"=>"bag",
"rate"=>1000,
"discount"=>0,
),
),
"status"=>"Y",
),
);
echo json_encode($a);
Thanks in advance.
Add one more array
//...
"address" => array(
array(
"line1"=>"abc",
"city"=>"abc",
// ...
),
)
I am trying to create json with php from two mysql tables:- Category(unique)- Subcategories or Rights(multiple in same category)But I can't list multiple subcategories under one category. Instead, for every subcategory new set of results is made that contains category data also.
This is php code:
$sql = "SELECT a.id as rid,a.name as rname,a.img as rimg,a.price,b.id as cid,b.name as cname FROM rights a INNER JOIN categories b ON a.category=b.id";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
$json_response = array();
while($row = $result->fetch_assoc()) {
$row_array['idCategory'] = $row['cid'];
$row_array['nameCategory'] = $row['cname'];
$row_array['rights'] = array([
'idRight' => $row['rid'],
'name' => $row['rname'],
'price' => $row['price'],
'image' => $row['rimg']
]);
array_push($json_response,$row_array);
}
echo json_encode($json_response);
}
With this I am getting:
[{
"idCategory": "1",
"nameCategory": "Cat1",
"rights": [{
"idRight": "1",
"name": "Right1 in Cat1",
"price": "10",
"image": "img1.jpg"
}]
}, {
"idCategory": "2",
"nameCategory": "Cat2",
"rights": [{
"idRight": "2",
"name": "Right1 in Cat2",
"price": "20",
"image": "img2.jpg"
}]
}, {
"idCategory": "2",
"nameCategory": "Cat2",
"rights": [{
"idRight": "3",
"name": "Right2 in Cat2",
"price": "30",
"image": "img3.jpg"
}]
}]
I tried changing mysql select with GROUP_CONCAT and GROUP BY but then I get data in one row like this:
"rights": [{
"idRight": "2,3",
"name": "Right1 in Cat2,Right2 in Cat2",
"price": "20,30",
"image": "img2.jpg,img3.jpg"
}]
But I need it like this:
[{
"idCategory": "1",
"nameCategory": "Cat1",
"rights": [{
"idRight": "1",
"name": "Right1 in Cat1",
"price": "10",
"image": "img1.jpg"
}]
}, {
"idCategory": "2",
"nameCategory": "Cat2",
"rights": [{
"idRight": "2",
"name": "Right1 in Cat2",
"price": "20",
"image": "img2.jpg"
},
{
"idRight": "3",
"name": "Right2 in Cat2",
"price": "30",
"image": "img3.jpg"
}]
}]
How to achieve that?
You need to remap your array and then initialize an array for the rights key... so, change your while loop something like this:
$json_response = array();
while($row = $result->fetch_assoc()) {
if (!isset($json_response[ $row['idCategory'] ])) {
$json_response[ $row['idCategory'] ] = [
'idCategory' => $row['idCategory'],
'nameCategory' => $row['nameCategory'],
'rights' => [],
];
}
$json_response[ $row['idCategory'] ]['rights'][] = [
'idRight' => $row['rid'],
'name' => $row['rname'],
'price' => $row['price'],
'image' => $row['rimg']
];
}
// We want the final result to ignore the keys and to create a JSON array not a JSON object
$data = [];
foreach ($json_response as $element) {
$data[] = $element;
}
echo json_encode($data);
This part of the code $json_response[ $row_array['idCategory'] ] helps to maintain a unique grouping of the data because it creates a hash based on the idCategory. An array can only have one key and since idCategory is always unique we can use that as the key for grouping on.
Then because we now have a hash-based array, we have to create a new array that is a 'real' array for when it is converted to JSON.
You do not want to use GROUP BY or GROUP_CONCAT in this situation.
I revised the code above to fit my needs, but I am having trouble to make another array of that array...
from:
...
$json_response[ $row['idCategory'] ]['rights'][] = [
'idRight' => $row['rid'],
'name' => $row['rname'],
'price' => $row['price'],
'image' => $row['rimg']
];
to:
$json_response[ $row['regCode'] ]['provinces'][] = $row['provDesc'];
actually this is a follow up question,
how about array inside array of that array...
like this:
[
{
rid: "1",
region: "REGION I", //array 1
provinces: [
{
pid: "128",
province: "ILOCOS NORTE", //array 2
cities[
"Adams", //array 3
"Bacarra"
],
"ILOCOS SUR"
]
},
{
rid: "2",
region: "REGION II",
provinces: [
"BATANES",
"CAGAYAN"
]
}
]