Hello I have decoded a json string that I sent to my server and Im trying to get the values from him.
My problem is that I cant get the values from the inner arrays.
This is my code:
<?php
$post = file_get_contents('php://input');
$arrayBig = json_decode($post, true);
foreach ($arrayBig as $array)
{
$exercise = $array['exercise'];
$response["exercise"] = $exercise;
$response["array"] = $array;
echo json_encode($response);
}
?>
When I get the answer from my $response I get this values:
{"exercise":null,"array":[{"exercise":"foo","reps":"foo"}]}
Why is $array['exercise'] null if I can see that is not null in the array
Thanks.
From looking at the result of $response['array'], it looks like $array is actually this
[['exercise' => 'foo', 'reps' => 'foo']]
that is, an associative array nested within a numeric one. You should probably do some value checking before blindly assigning values but in the interest of brevity...
$exercise = $array[0]['exercise'];
Because of the [{...}] you are getting an array in an array when you decode your array key.
So:
$exercise = $array['exercise'];
Should be:
$exercise = $array[0]['exercise'];
See the example here.
Related
So I got this array:
$list = simplexml_load_file('http://feu01.ps4.update.playstation.net/update/ps4/list/eu/ps4-updatelist.xml');
if($list) {
$data = array('firmware' => $list->region->system_pup[0]['label']);
header('Content-Type: application/json');
echo json_encode($data);
}
And it outputs this:
{"firmware":{"0":"5.01"}}
But there's also a zero there. How do I remove it from the array so it's like this:
{"firmware":"5.01"}
This is a SimpleXMLElement result which you need to convert to a string if you want that data:
$data = array('firmware' => (string) $list->region->system_pup[0]['label']);
In JSON form it looks like an associative array, which it isn't, so the [0] trick which normally works to navigate to it won't.
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?
I am facing a strange issue with my PHP code (I'm a beginner to PHP so apologies for my bad coding skills). Each array item in my JSON has a unique ID associated with it, to delete an array I just pass the unique ID to my code and it deletes the array item associated with it, but all my array items contain an integer field and that doesn't get deleted and it messes up my JSON (parsing fails when I try to do so later).
<?php
$var1 = filter_input(INPUT_POST, 'unique_id', FILTER_UNSAFE_RAW);
if ($var1 === null) {
die('The "unique_id" parameter is not set');
}
$data = file_get_contents('feed.json');
if ($data === false) {
die('An error occurred when opening "feed.json"');
}
$json = json_decode($data, true);
if ( ! isset($json[0]['unique_id'])) {
die("The JSON was not decoded correctly");
}
foreach ($json as $key => $value) {
if ($value['unique_id'] == $var1) {
unset($json[$key]);
}
}
$new_json_string = json_encode($json);
file_put_contents('feed.json', $new_json_string, JSON_UNESCAPED_SLASHES | LOCK_EX);
echo "Success";
?>
Here's the sample JSON:
[
{"student_id":"22222222","unique_id":"862916786a1340afbfdf23caa541963f","status":"Hey yo what's up","image":"none","likes":"0"},
{"student_id":"33333333","unique_id":"d237556a90d44b1397e9290cd8g09349","status":"Message from another student","image":"none","likes":22}
]
after deleting, I'm left with
{"1":{"student_id":"33333333","unique_id":"d237556a90d44b1397e9290cd8g09349","status":"Message from another student","image":"","likes":31}
As you can see {"1": is invalid and shouldn't be there.
Does anyone know what am I doing wrong?
EDIT: Here's my code to create a new array item in my JSON
$json = file_get_contents('feed.json');
$data = json_decode($json);
$data[] = array('student_id' => "$student_id", 'unique_id' => "$unique_id" ,'status' => "$status_txt", 'image' => "$image_link", 'likes' => "0");
file_put_contents('feed.json', json_encode($data), JSON_UNESCAPED_SLASHES | LOCK_EX);
This is a combination of two things:
There is no representation of sparse Arrays in JSON
JSON's arrays with [] can only have a comma-separated list of contiguous elements starting from index 0.
No type information distinguishes JSON arrays and JSON objects in PHP
Both of these things are stored as PHP's array type. JSON objects use the associative keys.
When you unset index 0 from your array, it becomes sparse. Now, the only way to encode something that has a something[1] but no something[0] in JSON is to have an object with a key "1".
PHP's JSON encoder allows this because the array you pass in is of the right type (array) to be serialized as a JSON object. So it does this.
Maybe you wanted to use array_splice to remove the array element instead of unset.
Use array_values() to convert array as notified by Cheery in comments.
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.
I've have this list of products in JSON that needs to be decoded:
"[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]"
After I decode it in PHP with json_decode(), I have no idea what kind of structure the output is. I assumed that it would be an array, but after I ask for count() it says its "0". How can I loop through this data so that I get the attributes of each product on the list.
Thanks!
To convert json to an array use
json_decode($json, true);
You can use json_decode() It will convert your json into array.
e.g,
$json_array = json_decode($your_json_data); // convert to object array
$json_array = json_decode($your_json_data, true); // convert to array
Then you can loop array variable like,
foreach($json_array as $json){
echo $json['key']; // you can access your key value like this if result is array
echo $json->key; // you can access your key value like this if result is object
}
Try like following codes:
$json_string = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
$array = json_decode($json_string);
foreach ($array as $value)
{
echo $value->productId; // epIJp9
echo $value->name; // Product A
}
Get Count
echo count($array); // 2
Did you check the manual ?
http://www.php.net/manual/en/function.json-decode.php
Or just find some duplicates ?
How to convert JSON string to array
Use GOOGLE.
json_decode($json, true);
Second parameter. If it is true, it will return array.
You can try the code at php fiddle online, works for me
$list = '[{"productId":"epIJp9","name":"Product A","amount":"5","identifier":"242"},{"productId":"a93fHL","name":"Product B","amount":"2","identifier":"985"}]';
$decoded_list = json_decode($list);
echo count($decoded_list);
print_r($decoded_list);