PHP Arrays. Trouble formatting result array - php

I am working on an API in PHP that sends JSON data in form of an array to an android app. I'm having issues in returning the JSON array in the format;
"sammury" : [
{ "ClientName": "Samuel", "OrdersTaken": 400 },
{ "ClientName": "James", "OrdersTaken": 20 },
{ "ClientName": "Ritah", "OrdersTaken": 9 }
]
I'm using a php server online and a mysql database. I have added an image showing how the data that is returned loks like. Any Assistance Will be highly appreciated

Here is a simple example for you how to send your desired response.
1) Create your object arrays
2) Push the objects into the data array (you can use loop to push objects to array) and then assign that data array to the response array and convert it to Json.
Please see the working code here
$data = [];
$obj = [
"ClientName"=> "Samuel",
"OrdersTaken"=> 400
];
array_push($data, $obj);
$response = [
"sammury"=> $data
];
$json = json_encode($response);
echo $json;

Related

JSON into PHP: access array data if each array has a different name

I am trying to access data from a JSON file, using PHP.
Here is what the JSON feed looks like:
[{
"performancesByDateDisplay":{
"2021-09-02":[{
"performanceId":10813388,
"performanceTime":"8:00 PM"
}],
"2021-09-03":[{
"performanceId":10813638,
"performanceTime":"8:00 PM"
}]
}
}]
And here is the code I am using to access the data:
foreach($json_output->performancesByDateDisplay as $events) {
$perfId = $events->performanceId;
}
But $perfId is not returning any value. I think it's because each array has a different "name" (for example "2021-09-02" in the first instance)? How do I access the data, without knowing in advance what this name will be (it's coming from an external json feed)?
Thanks!
Both the root of your JSON and each "$events" item is an array of objects, not just an object.
If you were to iterate each of these arrays for example, and access the objects inside one-by-one, you'd get the expected result:
foreach($json_output as $json_output_item){
foreach($json_output_item->performancesByDateDisplay as $events){
foreach($events as $event){
$perfId = $event->performanceId;
var_dump($perfId);
}
}
}
Output:
int(10813388)
int(10813638)
Did you forget to decode?
Well, first you need to decode the JSON data into a native PHP structure.
$decodedJson = json_decode($json_output, true);
Then you can access it just how you'll access a native PHP array and associative array. Notice the true, that's to decode the JSON string into an associative array. Also, it'd be better to just get inside the array while decoding, hence making the above statement:
$decodedJson = json_decode($json_output, true)[0];
Now you can iterate over it.
foreach($decodedJson as $events) {
foreach($events as $date => $event) {
$perfId = $event[0]['performanceId'];
}
}

Simple array access (or list) doesn't work

I have a very simple problem that I unfortunately can't solve.
I use an API that returns an object that I convert to json to push it into my database, but I can't access the elements of this array (I don't know if it's multi-dimensional or not).
This is the json :
[
[
5.788894,
46.391834
],
[
5.788879,
46.392345
],
[
5.788877,
46.39241
]
]
And this this the object of the API :
API object
How should my loop be to retrieve the latitude and longitude of each point?
Thank you very much for your help;)
If I don't misunderstood your question and requirements then lets try like this way,
<?php
$json = '[[5.788894,46.391834],[5.788879,46.392345],[5.788877,46.39241]]';
$array = json_decode($json,1); // decode json to array
//just for debug
print '<pre>';
print_r($array);
print '<pre>';
foreach($array as $row){
echo "latitude = $row[0] and longitude = $row[1]".PHP_EOL;
}
DEMO: https://3v4l.org/U1F1n

getting error while converting json arry

from angularjs 2 my application getting below json value but i am not able to convert this json value to an array.
$response = '{username: "mosh", time: "2017-01-22T11:28:54.422Z"}';
$json_arrya = json_decode($response,true);
var_dump($json_arrya);
current output: NULL
expected output as an array
Try the json below
{
"username": "mosh",
"time": "2017-01-22T11:28:54.422Z"
}
to see if that works.
Also, this is a json object not an array so you might have to pass it as an array from your angular service like
[{ "username": "mosh", "time": "2017-01-22T11:28:54.422Z"}]

How to encoding multiple json object in php

I am working on a project where a user has to fill up a form and can upload multiple documents. Everytime he uploads a document, he calls a webservice which returns a JSON file with id and type.
Since he can upload multiple documents so the webservice is called many times. When he completes his form and submits it, I need to send a json with the multiple id and type that I have received previously from JSON.
This is the JSON that I need to send to the server when the user finally submits the form:
"docls":[
{
"id":"123",
"ty":"101",
},
{
"id":"456",
"ty":"102",
}
],
How do I encode the JSON when I dont know how many files the user has uploaded?
P.S. I have already been able to get the response from the first JSON in the form of 'id' and 'ty'. Do I need to store it in array? If yes then how do I decode it into json?
$json_string = array(
'docls' => array (
'id' => '123',
'ty' => '101',
),
);
You're going to want to build the array with php then json_encode it when your ready to send it back to the server
// Create an array to hold the documents
$documents = [];
// push each document into the array as the user does their thing
$documents[$id] = $ty;
// When the user is finished
$json = json_encode($documents);
Well, you just have to use json_decode to convert json string you receive to php array, and json_encode to convert convert php array to json formatted string.
Check this example:
<?php
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
?>
more information here

How to create a JSON array in php?

I am trying to create a simple android application that takes data from a database and displays it in a list format on the android screen. I made a php script that queries the database and returns a json object. I convert the json object into json array and extract the relevant data for display. But I am getting this error "JSONException: type org.json.JSONObject cannot be converted to JSONArray".
Following is my php script -
// response Array
$response = array("tag" => $tag, "success" => 0, "error" => 0);
$username = $_POST['username'];
$events = $db->viewAttendingEvent($username);
if ($events) {
$response["success"] = 1;
$response["event"]["owner"] = $events["owner"];
$response["event"]["friendsnames"] = $events["friendsnames"];
$response["event"]["vote"] = $events["vote"];
$response["event"]["accepted"] = $events["accepted"];
$response["event"]["eventname"] = $events["eventname"];
$response["event"]["eventnumber"] = $events["eventnumber"];
$response["event"]["created_at"] = $events["created_at"];
echo json_encode($response);
This is the json which I receive back :
{
"tag": "view_invitations",
"success": 1,
"error": 0,
"event": {
"owner": "jkkkkoopp",
"friendsnames": "don",
"vote": "0",
"accepted": "f",
"eventname": "yyy",
"eventnumber": "11",
"created_at": "2014-05-29 22:27:31.843528"
}
}
I am trying to extract 'event' from this json object, which is not an array.
it should be
{
"event": [
{
"owner": "jkkkkoopp",
"friendsnames": "don",
"vote": "0",
"accepted": "f",
"eventname": "yyy",
"eventnumber": "11",
"created_at": "2014-05-2922: 27: 31.843528"
}
]
}
Can someone help me how to make this a valid jsonArray ? Thanks
If you're looking to get a JavaScript 'Array' (from which I mean an Object with nothing but integer keys) then you need to only have integer keys in your PHP Array.
This article is a pretty good resource and explains some of the differences between arrays and objects in javascript. The relevant quote here comes from the What Arrays Are section (emphasis mine):
Javascript arrays are a type of object used for storing multiple
values in a single variable. Each value gets numeric index and may be
any data type.
No it should not be what you proposed it should be. If that were the case you would have to have your php be this:
$response["event"][0]["owner"] = $events["owner"];
$response["event"][0]["friendsnames"] = $events["friendsnames"];
$response["event"][0]["vote"] = $events["vote"];
$response["event"][0]["accepted"] = $events["accepted"];
$response["event"][0]["eventname"] = $events["eventname"];
$response["event"][0]["eventnumber"] = $events["eventnumber"];
$response["event"][0]["created_at"] = $events["created_at"];
The way you have it now is event is an associative array so it converts it to an object. You are expecting that event = an array of objects. So you need to either change your php code to make event be an array of objects (as demonstrated above) or you need to modify your expectations to have event = an object.

Categories