I'm populating an array like this:
$POarray = array();
foreach($orders as $order)
{
$total = OrderItems::where('OrderID', $order->OrderID)->sum('TotalPrice') * (1 + $LRmarkup);
$arraydata = array(
'Name' => $order->OrderNumber,
'Total' => $total);
$POarray[] = $arraydata;
}
This results in the contents of the $POarray variable being:
[
{
"Name": "DS-BS-18102654",
"Total": 241.4655
},
{
"Name": "test test",
"Total": "600.00"
}
]
I am attempting to access this data like this:
$purchase1name = $POarray[0]->Name;
$purchase1total = $POarray[0]->Total;
And I am getting this error:
"Trying to get property of non-object"
Shouldn't this work?
Thank you for taking the time to respond.
$POarray is not an object.
Try:
$purchase1name = $POarray[0]['Name'];
$purchase1total = $POarray[0]['Total'];
You need to do this way after decoding it using json_decode(),
<?php
$key='[
{
"Name": "DS-BS-18102654",
"Total": 241.4655
},
{
"Name": "test test",
"Total": "600.00"
}
]';
$POarray = json_decode($key);
echo $POarray[0]->Name;
echo $POarray[0]->Total;
?>
DEMO: https://3v4l.org/JvCam
You can also use this.
array_get($POarray[0], 'Name');
array_get($POarray[0], 'Total');
For more information: https://laravel.com/docs/5.7/helpers
Related
I have a json response like below:
$response ='[
{
"userSummaries": [
{
"id": "9910",
"status": "Active",
"name": "Jhon"
}
]
},
{
"userSummaries": [
{
"id": "8754",
"status": "Active",
"name": "Jane"
}
]
}
]';
and I would like to group this by userSummaries with this php code:
$myArr = json_decode($response, true);
$result_arr = [];
array_walk($myArr,function($v,$k) use (&$result_arr){
$result_arr[key($v)] = $v[key($v)];
});
echo json_encode($result_arr);
and the response only return one data:
{"userSummaries":[{"id":"8754","status":"Active","name":"Jane"}]}
Is it possible to get the output response like this?:
{"userSummaries":[{"id":"9910","status":"Active","name":"Jhon"}, {"id":"8754","status":"Active","name":"Jane"}, ]}
Tried over the net but I did not found the solutions
here my script for this: https://3v4l.org/tVkK5
also tried this:
$class_array = array();
foreach ($myArr as $sa) {
$class_array[$sa['userSummaries']][] = array('name' => $sa['name']);
}
but return:
Notice: Undefined index: name in /in/hvSFC on line 28
Warning: Illegal offset type in /in/hvSFC on line 28
Notice: Undefined index: name in /in/hvSFC on line 28
Warning: Illegal offset type in /in/hvSFC on line 28
[]
need help
You were close. You just needed to reference the key and first of userSummaries in each loop, instead of working with the whole...
$myArr = json_decode($response, true);
$result_arr = ["userSummaries"=>[]];
foreach($myArr as $user) {
$result_arr["userSummaries"][] = $user['userSummaries'][0];
}
echo json_encode($result_arr);
Results in:
{"userSummaries":[
{"id":"9910","status":"Active","name":"Jhon"},
{"id":"8754","status":"Active","name":"Jane"}
]}
If you foresee that userSummaries in each will have multiple users themselves... then this would work:
$response ='[
{
"userSummaries": [
{
"id": "9910",
"status": "Active",
"name": "Jhon"
}
]
},
{
"userSummaries": [
{
"id": "8754",
"status": "Active",
"name": "Jane"
},
{
"id": "5421",
"status": "Active",
"name": "Bob"
}
]
}
]';
$myArr = json_decode($response, true);
$result_arr = ["userSummaries"=>[]];
foreach($myArr as $usergroup) {
foreach($usergroup['userSummaries'] as $user) {
$result_arr["userSummaries"][] = $user;
}
}
echo json_encode($result_arr);
Results in:
{"userSummaries":[
{"id":"9910","status":"Active","name":"Jhon"},
{"id":"8754","status":"Active","name":"Jane"},
{"id":"5421","status":"Active","name":"Bob"}
]}
Hello I am trying to break down JSON data
** {
"message": "gradeExam.php",
"id": "171",
"student_id": "dfd",
"questions": [{
"question_id": "0",
"student_input": "def doubly_"
},
{
"question_id": "1",
"student_input": "asd"
}
]
}**
using PHP
$json = file_get_contents('php://input');
$_POST = json_decode($json, true);
$input = $_POST["questions"];
foreach($input as $questions)
{
$quest_id[] = $questions["question_id"];
$student_input[] = $questions["student_input"];
}
echo $quest_id;
echo $student_input;
BUT keep getting a response of.. ArrayArrayArray[]
I am trying loop and get the data of question_id: 0, student_input: def doubly_, question_id: 1, student_input: asd.
What am I doing wrong?
Everything that you have done is correct except these 2 lines.
echo $quest_id;
echo $student_input;
As $quest_id and $student_input are arrays we cannot use the echo function. Instead, you can use the print_r function as below
print_r($quest_id);
print_r($student_input);
I was wondering if someone could help please. I have a JSON feed from an API, and I can never figure out the levels to get the information I need?
the JSON is below
{
"sourceId": "1234",
"sourceType": "MONITOR",
"searchMeta": {
"startTimestamp": 1462361513,
"endTimestamp": 1462508560,
"maxResults": 10000,
"metricType": [
"clients"
],
"family": [
"Product"
],
"metricsInterval": "M5"
},
"clients": {
"One": [
{
"timestamp": 1462361400,
"avg": 2,
"min": 1,
"max": 3,
"probes": 6,
"samples": 3,
"sources": [
"123",
"234",
"345",
"456",
"567",
"789"
]
},
I was wanting to get the Probes value and the Samples value into a variable
foreach($json['clients'] as $range => $product){
echo $product['timestamp']." Probes: ".$product['probes']." Samples: ".$product['samples']." <br>";
}
Thanks in advance
I assume you'll have a range of clients (hence the loop). So you'll need to loop each client too as it's an array of object's.
If you visualise it, that looks like this:
CLIENTS = ARRAY(
1 => ARRAY( OBJECT{} ), // you want the OBJECT{}
....etc
)
So the below loop will get it for you.
$data = json_decode($json, TRUE);
foreach($data['clients'] as $range => $product) {
foreach($product as $element){
echo $element['timestamp']." Probes: ".$element['probes']." Samples: ".$element['samples']." <br>";
}
}
Example/Demo
Returns the following:
1462361400 Probes: 6 Samples: 3 <br>
Try this.
$data = json_decode($json,true);
foreach($data['clients'] as $client){
echo $client['timestamp']." Probes: ".$client['probes']." Samples: ".$client['samples']." <br>";
}
The demand of OP:
I was wanting to get the Probes value and the Samples value into a
variable
Simple just name your json file as $json.
$arr = json_decode($json);
echo $samples = $arr->clients->One[0]->samples; //3
echo $probes = $arr->clients->One[0]->probes; //6
suppose I have an Array like this :
$myArray =
[
{
"id": 86,
"name": "admin/login"
},
{
"id": 87,
"name": "admin/logout"
},
{
"id": 88,
"name": "admin/desktop"
}
]
Each element of array has json format. and now I want to get name of element that have id of 87 for example.
Firstly How can I found that is there element with this id then get name property of that?
Decode JSON string into array. Then use Laravel's array_first method.
<?php
$myArray = '[{"id": 86,"name": "admin/login"},{"id": 87,"name": "admin/logout"},{"id": 88,"name": "admin/desktop"}]';
// Decode into array
$array = json_decode($myArray, true);
// Find item with correct id
$result = array_first($array, function($key, $value){
return $value['id'] === 87;
}, false);
if ($result) {
echo 'Item found, it\'s name is: '.$result['name'];
}
If you have id you like to find in variable, you have to use use construct.
// ID to search for
$searchID = 87;
// Find item with correct id
$result = array_first($array, function($key, $value) use($searchID){
return $value['id'] === $searchID;
}, false);
Try using this:
$newArray = json_decode($myArray);
and you'll get type of array
[
[
"id"=> 86,
"name"=> "admin/login"
],.....
........
]
Your $myArray is incorrect so, assuming it is a json string you can do this in the following way :
At first json_decode it into an arry.
Loop through the elements to find out you desired value(87).
Keep a flag which will tell if you have actually found any value.
<?php
$myArray =
'[
{
"id": 86,
"name": "admin/login"
},
{
"id": 87,
"name": "admin/logout"
},
{
"id": 88,
"name": "admin/desktop"
}
]';
$myArray = json_decode($myArray , true);
$found = 0;
foreach($myArray as $anArray)
{
if($anArray['id'] == 87)
{
var_dump($anArray['name']);
$found = 1;
}
}
if($found == 1)
{
var_dump("Element found.");
}
else
{
var_dump("Element not found. ");
}
?>
I feel terrible even asking because I have been TRYING to understand and comprehend other peoples examples this is what i'm TRYING to accomplish
{
"field": [
{
"appid": 0,
"page": 0,
"fieldname": "Sweet",
"value": "Tammy Howell"
},
{
"appid": 1,
"page": 1,
"fieldname": "Cecilia",
"value": "Shana Jordan"
},
{
"appid": 2,
"page": 2,
"fieldname": "Merritt",
"value": "Copeland Pena"
}
]
}
I need to be able to make the above JSON output happen when doing an SQL SELECT statement
Here is my currentCode
$x = 0;
$userFieldsResult = mysqli_query($database_id, "SELECT * FROM theDB.DynamicFields ORDER BY Page, Priority") or die (mysqli_error($database_id));
if (mysqli_num_rows($userFieldsResult)<=0)
{
echo "nothing found";
exit;
} else
{
while($row = mysqli_fetch_array($userFieldsResult))
{
$userFields[$x]['appid'] = $row['appid'];
$userFields[$x]['page'] = $row['page'];
$userFields[$x]['fieldname'] = $row['fieldname'];
$userFields[$x]['value'] = $row['value'];
$x++;
}
echo json_encode($userFields);
exit;
}
echo json_encode($userFields);
This is normally how i just been outputting json so they each are just part of 1 array looping, but I am trying to understand how to create more "in-depth" JSON arrays so they have a specific identifier before they list out the information.
[
{
"appid": 0,
"page": 0,
"fieldname": "Sweet",
"value": "Tammy Howell"
},
{
"appid": 1,
"page": 1,
"fieldname": "Cecilia",
"value": "Shana Jordan"
},
{
"appid": 2,
"page": 2,
"fieldname": "Merritt",
"value": "Copeland Pena"
}
]
In my example I just want to be able to have "field" be the "upper" part of the array that holds all the information as i showed in the example above.
You need to add field as parent array to your array.
Change from
echo json_encode($userFields);
Into
$json = array('fields' => $userFields);
echo json_encode($json);
In this particular configuration, you are being returned an object with properties, of which, the property's value may be an array.
So what you should actually be doing is creating a stdClass object in PHP and assigning it a property of "field" which is an empty array. Then you can push into this array stack.
$obj = new stdClass();
$obj->fields = array();
while(....){
$obj->fields[$x]['appid'] =
$obj->fields[$x]['appid'] = $row['appid'];
$obj->fields[$x]['page'] = $row['page'];
$obj->fields[$x]['fieldname'] = $row['fieldname'];
$obj->fields[$x]['value'] = $row['value'];
}
Now you can json encode the object and return it.
echo json_encode($obj);