I have this part of a JSON file:
And the next record:
I need to get several fields from each record. For instance [City].
With this code I can get the first city:
$response = curl_exec($ch);
$result = json_decode($response, true);
echo $result['GetLocationsResult']['ResponseLocation'][0]['Address']['City'];
However I want to loop through all the records and get all [City] fields.
This should be quite straight forward
$locations = $result['GetLocationsResult']['ResponseLocation'];
$cities = [];
foreach($locations as $location)
{
$cities[] = $location['Address']['City'];
}
var_dump($cities);
This is a more modern approach to getting all the cities, we don't need any loop anymore:
$cities = array_map(
fn($location) => $location['Address']['City'],
$result['GetLocationsResult']['ResponseLocation']
);
print_r($cities);
It depends on what exactly you need from the array whether this suits.
The true param of the json_decode tells you that the decoded json is an associative array. Thus you can use it as an array an loop over the values you want as you would threat any other array.
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 6 years ago.
How can i split that image or assign an array in PHP.
[{"ID":2,"no":123,"pname":"400","unit":"mt","bid_count":"4568","unit_price":"56","est_unit_price":"21.31","progress_count":"3841","i_project":117,"seq":0}]
I tried to split but it is a little weird.
I use this =>
$object = str_replace('[{', '', $object);
$object = str_replace('}]', '', $object);
$pieces = explode(",", $object);
// return $pieces[0];
$datas = array(
'ID' =>str_replace('"ID":','',$pieces[0]),
'poz_no'=>str_replace('"poz_no":','',$pieces[1]),
'poz_name'=>"asd",
'unit'=>str_replace('"unit":','',$pieces[3]),
'bid_count'=>str_replace('"bid_count":','',$pieces[4]),
'unit_price'=>str_replace('"unit_price":','',$pieces[5]),
'est_unit_price'=> str_replace('"est_unit_price":','',$pieces[6]),
'progress_count' =>str_replace('"progress_count":','',$pieces[7]),
'i_project'=>str_replace('"i_project":','',$pieces[8]),
'seq' =>str_replace('"seq":','',$pieces[9])
);
I did it myself but it seems weird:
$object = str_replace('[{', '', $object);
$object = str_replace('}]', '', $object);
$pieces = explode(",", $object);
$datas = array(
'ID' =>str_replace('"','',str_replace('"ID":','',$pieces[0])),
'poz_no'=>str_replace('"','',str_replace('"poz_no":','',$pieces[1])),
'poz_name'=>str_replace('"','',str_replace('"poz_name":','',$pieces[2])),
'unit'=>str_replace('"','',str_replace('"unit":','',$pieces[3])),
'bid_count'=>str_replace('"','',str_replace('"bid_count":','',$pieces[4])),
'unit_price'=>str_replace('"','',str_replace('"unit_price":','',$pieces[5])),
'est_unit_price'=>str_replace('"','',str_replace('"est_unit_price":','',$pieces[6])),
'progress_count' =>str_replace('"','',str_replace('"progress_count":','',$pieces[7])),
'i_project'=>str_replace('"','',str_replace('"i_project":','',$pieces[8])),
'seq' =>str_replace('"','',str_replace('"seq":','',$pieces[9]))
);
You can use json_decode for this.
If you have your string:
$json = '[{"ID":2,"poz_no":123,"poz_name":"400mm Muflu Beton ve C Parçası Döşenmesi","unit":"mt","bid_count":"4568","unit_price":"56","est_unit_price":"21.31","progress_count":"3841","i_project":117,"seq":0}]';
You can simply do:
$datas = json_decode($json, true);
Now in $datas you have an array with all the fields from json.
As you can see in json you have an array of objects with only one element. If you want only that first element you can do after:
$datas = $datas[0]; //get first element of array.
Your are actually dealing with a JSON encoded Data here. So, you may need to first convert the JSON Data to Standard PHP Object. And then you can simply access your preferred values using normal PHP Object Access Notation. The commented Code below attempts to illustrate (however vaguely) the Idea.
THE GIVEN JSON DATA:
<?php
$jsonString = '[{
"ID":2,
"poz_no":123,
"poz_name":"400mm Muflu Beton ve C Parçası Döşenmesi",
"unit":"mt",
"bid_count":"4568",
"unit_price":"56",
"est_unit_price":"21.31",
"progress_count":"3841",
"i_project":117,
"seq":0
}]';
THE PROCEDURE:
<?php
// CONVERT THE JSON DATA TO NATIVE PHP OBJECT...
$arrJSONData = json_decode($jsonString);
// NOW, YOU COULD ACCESS THE PHP OBJECT BY DOING: $arrJSONData[0]
$objJson = $arrJSONData[0];
// IF YOU DID IT LIKE THIS; FROM THIS POINT YOU COULD ACCESS YOUR DATA
// LIKE YOU WOULD ACCESS ANY NORMAL PHP OBJECT LIKE SO:
$id = $objJson->ID;
$pozNo = $objJson->poz_no;
$unit = $objJson->unit;
// HOWEVER, WHAT IF THE JSON DATA CONTAINS MORE THAN ONE ENTRY?
// THEN A LOOP WOULD BE NECESSARY...
// LOOP THROUGH THE RESULTING ARRAY OF OBJECTS AND GET YOUR DATA...
foreach($arrJSONData as $jsonData){
// AGAIN; YOU COULD ACCESS YOUR DATA
// LIKE YOU WOULD ACCESS ANY NORMAL PHP OBJECT LIKE SO:
$id = $objJson->ID;
$pozNo = $objJson->poz_no;
$unit = $objJson->unit;
}
I'm working with Laravel 5 right now and I have the following problem. I've got response from DB query:
[{"id":1}]
and I want to take out 1 as int or string. Any ideas?
I've tried to solve this like follows:
$json = (DB query);
$data = json_decode($json);
$final = $data[0]->id;
and response is :
json_decode() expects parameter 1 to be string, array given
This is all you need.
$response = json_decode($response); // Decode the JSON
$string = $response[0]->id; // Save the value of id var
As you say, the string you have is in JSON format, so you need to use json_decode to access it in PHP.
The square brackets refer to an array, and the braces refer to an object within that array, so what you're looking for is the id value of the first element (i.e. element 0) in the array.
<?php
$json = '[{"id":1}]';
$data = json_decode($json);
echo $data[0]->id;
// 1
Try this
$json_array = '[{"id":1}]';
$data = json_decode($json_array);
print_r($data); // To display the result array
You just need to decode it, if I'm not misunderstanding your questions.
$json = '[{"id":1}]';
$decodedObject = json_decode($json);
Then you can loop through the aray and do something with your data:
foreach($decodedObject as $key => $value) {
$id = $value->id;
}
If you're using Laravel, though, why not use Eloquent models?
Although this may seem like a general question, how can you extract content from a URL such as (http://api.openweathermap.org/data/2.5/weather?q=London,uk) so that it can be formatted and used in the form of an array for each element in PHP? More specifically, how can I extract information from websites in general?
To get data from URL:
$content = file_get_contents('http://api.openweathermap.org/data/2.5/weather?q=London,uk');
Convert it in simple array:
$new_data = json_decode($content, true);
print_r($new_data);
$json = file_get_contents('http://api.openweathermap.org/data/2.5/weather?q=London,uk');
$array = json_decode($json, true);
var_dump($array);
I have three arrays example: $array1,$array2,$array3.
I want to insert the array2 and array3 in two different columns in the same table.
can i do that?
here is the code below that i am trying but it does not work for me i am doing in codeigniter:
controller:
$athletes_id = $this->input->post('athletes'); // array 1
$fields_id = $this->input->post('fields_id'); // array 2
$athlete_score = $this->input->post('athlete_score'); // array 3
$id = array();
foreach($athlete_score as $row){
$additional_data = array(
'test_reports_id' => $test_report_id,
'score' => $row,
);
$id[] = $this->test_model->save_test_reports_details($additional_data);
}
for($j=0;$j<count($fields_id);$j++){
$data2 = array('fields_id' => $fields_id[$j]);
$this->test_model->update_test_reports_details($id,$data2);
}
Model :
public function update_test_reports_details($id,$data2){
$this->db->where_in('id',$id);
$this->db->update('test_reports_details',$data2);
}
Just serialize the arrays.
$data2 = serialize($array2); // or whatever array you want to store
Then to retrieve with unserialize
$array2 = unserialize($data2);//or the row index
To store array in database you have to serialize it.
Try :
public function update_test_reports_details($id,$data2){
$this->db->where_in('id',$id);
$this->db->update('test_reports_details',serialize($data2));
}
To unserialize it when you get it from the database you have to use unserialize()
You can serialize as suggested in other answers, however I personally prefer to json_encode the array.
$data = json_encode($array);
And when you are reading in the model you should decode the data:
$array = json_decode($data, true); // set second argument to true to get an associative array
Using JSON has the advantage of better readability while still in the DB. This might not seem like much, but it can really help in some cases.