How do i create json array of object usingthe php code? - php

for($i=0;$i<count($storetag);$i++){
$user=mysqli_query($con,"select user_id,profile_image_url from Wheel_User where user_id='$storetag[$i]'");
if(mysqli_num_rows($user)==0){
//For failure status if session id is wrong.
//http_response_code(404);
echo json_encode(array("status"=>"404","error"=>"Sorry, post id does not exists.".die()));
}
else{
$json_responce1=array();
while ($row = $user->fetch_array()){
$row_array['user_id'][$i]=explode(',',$row['user_id']);
$row_array['profile_image_url'[$i]=$row['profile_image_url'];
}
}
}
array_push($json_responce1,$row_array);
echo str_replace('\/','/', json_encode(array($json_responce1)));
It returns the following JSON
{
user_id: [3]
"1234",
"31332",
"12412"
profile_image_url: [3]
"localhost/1234.com",
"localhost/2345.com",
"localhost/3456.com"
}
but i want the json format like this
"user_id":[
{
"id":"1234",
"url":"localhost/1234.com"
},
{
"id":"1234",
"url":"localhost/1234.com"
},
{
"id":"1234",
"url":"localhost/1234.com"
}
]

You want to organise your array slightly different.
Try this
$row_array['user_id'][$i]['id']=explode(',',$row['user_id']);
$row_array['user_id'][$i]['url']=$row['profile_image_url'];
Everything should be within user_id and then by putting the $i before $id and $url, you will be grouping them as required.

Related

I have a json object and I want to push that object into the entries array. So the expected output is shown below. How to do this in PHP?

Need to insert the object in the entries array using array_push method of php where the value for test_view_id will be coming from another array. Can anyone please tell the syntax to do so.
$testViewId = array(12,13,14);
sample object
{
"miscResourceProperties":{
"test_view_id":12
}
}
Expected Output
$data = {
"eventStartTime":1656863552,
"entries":[
{
"miscResourceProperties":{
"test_view_id":12
}
},
{
"miscResourceProperties":{
"test_view_id":13
}
},
{
"miscResourceProperties":{
"test_view_id":14
}
}
]
}

How to filter and restructure json data with php?

I couldn't find an answer, so I decided to ask.
I get this response from an API:
[
{
"seasonNumber":1,
"numWins":1,
"numHighBracket":2,
"numLowBracket":2,
"seasonXp":111,
"seasonLevel":5,
"bookXp":0,
"bookLevel":1,
"purchasedVIP":false
},
{
"seasonNumber":2,
"numWins":1,
"numHighBracket":21,
"numLowBracket":31,
"seasonXp":1651,
"seasonLevel":25,
"bookXp":9,
"bookLevel":11,
"purchasedVIP":false
},
{
"seasonNumber":3,
"numWins":9,
"numHighBracket":57,
"numLowBracket":127,
"seasonXp":4659,
"seasonLevel":68,
"bookXp":0,
"bookLevel":100,
"purchasedVIP":true
},
{
"seasonNumber":4,
"numWins":8,
"numHighBracket":19,
"numLowBracket":36,
"seasonXp":274,
"seasonLevel":33,
"bookXp":7,
"bookLevel":35,
"purchasedVIP":true
}
]
I am trying to change the json data to this:
{
"seasons":
[
{
"season":1,
"battle_pass":false
},
{
"season":2,
"battle_pass":false
},
{
"season":3,
"battle_pass":true
},
{
"season":4,
"battle_pass":true
}
]
}
In my current code I am using regex like this:
preg_match_all("/(?:\{\"seasonNumber\"\:(\w)|purchasedVIP\"\:(\w+))/", $response, $seasons);
echo '{"seasons":'.json_encode($seasons, JSON_FORCE_OBJECT, JSON_PRETTY_PRINT).'}';
It's basically putting everything in a separate array but that's not what I want.
Decode the json, restructure the data, re-encode.
Code: (Demo)
// your $json =
foreach (json_decode($json) as $set) {
$array[] = ["season" => $set->seasonNumber, "battle_pass" => $set->purchasedVIP];
}
echo json_encode(["seasons" => $array]);
Output:
{"seasons":[{"season":1,"battle_pass":false},{"season":2,"battle_pass":false},{"season":3,"battle_pass":true},{"season":4,"battle_pass":true}]}
p.s. if you want to force objects and pretty print, separate those flags with a pipe (|). https://3v4l.org/qsPb0

Correct check JSON with arrays in Codecept

Little issue, how to correct check JSON, recieved with GET by codeception.
Here it come..
{
"brands":[
{
"letter":"b",
"list":[
{
"text_ident":"brand1",
"title":"brand1",
"shortDescription":"brand1brand1"
},
{
"text_ident":"brand2",
"title":"brand2",
"shortDescription":"brand2brand2"
},
{
"text_ident":"brand3",
"title":"brand3",
"shortDescription":"brand3brand3"
}
]
},
{
"letter":"v",
"list":[
{
"text_ident":"vrand3",
"title":"vrand3",
"shortDescription":"vrand3vrand3"
}
]
}
]
}
And here is the BrandsMenuCept.php test
I start it with...
$fix = new app\tests\api\v1\fixtures\BrandsFixture();
$fix->load();
$I = new ApiTester($scenario);
$I->wantTo('test GET v1/brands/menu');
$I->sendGet('http://example.com/v1/brands/menu');
$I->seeResponseCodeIs('200');
$I->seeResponseIsJson();
$I->seeResponseJsonMatchesJsonPath('$.brands');
...
And what i should write after, how to check multiple arrays?
You can do this way:
First json_decode the response with true parameter like this
$responsearr=json_decode($json, true);
Then you can check the count of the array like this:
if(count($responsearr)>0){
//logic follows here...
}else{
//invalid json message comes here
}

Changing how returned json response looks

I'm trying to return a Json array and it works, but the other application I'm using the API for can't accept the format that the json is printed it (the way it looks, that is).
Example:
{
"123": [
{
"id": 1
}
]
}
But I need it to be:
"123":
{
"id": 1
}
Using this code:
$param = 123;
$array = User::all();
return \Response::json([$param => $array], 200, array(), JSON_PRETTY_PRINT);
Is this possible to do somehow?
I guess what you want is:
{
"123":
{
"id": 1
}
}
If you are sure you want to send just a single user, and not an array of users you can do:
$param = 123;
$user = User::first(); //Or any other Eloquent query, which gets the exact user you want
return response()->json([$param => $user]);

How to iterate the JSON data into a loop using PHP?

I need to iterate some JSON formatted data into loop using PHP. My JSON data is below:
{
"question1":{
"ques":"questin1",
"optional":[
{
"opt":"option1"
},
{
"opt":"option2"
}
]
},
"question2":{
"ques":"questin2",
"optional":[
{
"opt":"option1"
},
{
"opt":"option2"
}
]
}
}
I need to run the loop so that the result data will come in above format using PHP.
Convert the php object to json object using json_encode
// convert object => json
$json = json_encode($myObject);
This might helpful: https://stackoverflow.com/a/9858457/6285410
What you showed us is a Possible JSON Data. In this Format, we can do nothing with it in PHP except by decoding back into Native PHP Object. Once that is done, You can access all the Properties of the Object like you do with normal PHP Object like $objData->questin1. Here's what is meant with the above statements:
<?php
$strJson = '{
"question1":{
"ques":"questin1",
"optional":[
{
"opt":"option1"
},
{
"opt":"option2"
}
]
},
"question2":{
"ques":"questin2",
"optional":[
{
"opt":"option1"
},
{
"opt":"option2"
}
]
}
}';
$objData = json_decode($strJson);
var_dump($objData);
// NOW, TO GET AT EACH OF THE PROPERTIES OF THE OBJECT IS EASY...
// ACCESS THE question1 OR question2
$q1 = $objData->question1;
$q2 = $objData->question2;
// ACCESS THE que WITHIN question 1 OR question2
$k1 = $objData->question1->ques; // EQUIVALENT TO: $q1->ques
$k2 = $objData->question2->ques; // EQUIVALENT TO: $q2->ques
// ACCESS THE optional ARRAY INSIDE OF question 1 OR question2
$opt1 = $objData->question1->optional; // EQUIVALENT TO: $q1->optional
$opt2 = $objData->question2->optional; // EQUIVALENT TO: $q2->optional
var_dump($q1, $q2, $k1, $k2, $opt1, $opt2);
?>

Categories