how to Access to nested items in JSON with foreach PHP? - php

I have the following JSON structure
{"Id":"1","Persons":[{"Name":"Carl","Time":"00:00:03","info":"","Timeext":"","Timeout":"","Timein":""}, {"Name":"Carl","Time":"00:00:03","info":"","Timeext":"","Timeout":"","Timein":""}{"Name":"Luis","Time":"00:00:08","info":"","Timeext":"","Timeout":"","Timein":""}]}
How I can have acces or read the item inside the nest? For example if I just want the value of time for Carl or all information about Carl. Till now I just can get without a problem the single item in the collection 'Id'. The rst nested items not.
I tryed with json_decode like this:
if( $_POST ) {
$arr['Id'] = $_POST['Id'];
$arr['NP'] = $_POST['NP'];
$jsdecode = json_decode($arr);
foreach ($jsdecode as $values){
echo $values->Time;
}
Can PLEASE somebody help me?

if( $_POST ) {
$arr['Id'] = $_POST['Id'];
$arr['NP'] = $_POST['NP'];
$jsdecode = json_decode($arr,true);
foreach ($jsdecode as $values){
echo $values->Time;
}
Adding 'true' to json_decode converts it to array

You are processing it correct , Just add true as the second parameter to json_decode which will be converted to an Array like
$jsdecode = json_decode($arr,true);

Related

Getting values from key value pairs PHP

I have a registration form which saves user data to a text file via the serializable method.
a:1:{i:0;s:44:"{"name":"Mario","pw":"3214","email":"mo#mo"}";}
I can deserialize the data however I am having some trouble extracting the value "Mario" from the key - "name". Code can be seen below:
$array = file_get_contents('user.txt');
$artikel = unserialize($array);
foreach ($artikel as $item ){
echo $item['name'];
}
The error I recieve is Illegal string offset 'name'. Any help would be greatly appreciated.
You have a serialized array of JSON strings.
So try like this
//$array = file_get_contents('user.txt');
$artikel = unserialize('a:1:{i:0;s:44:"{"name":"Mario","pw":"3214","email":"mo#mo"}";}');
//print_r($artikel);
foreach ($artikel as $item ){
$json = json_decode($item);
echo $json->name;
}
PS: Storing a password in plain text is very bad security, storing that in a simple file is even worse security, so I hope system this will never actually be used. PHP provides password_hash()
and password_verify() please use them.
You need to json_decode after foreach with true as a second parameter then you will get array as you want..
<?php
$arr = 'a:1:{i:0;s:44:"{"name":"Mario","pw":"3214","email":"mo#mo"}";}';
$artikel = unserialize($arr);
foreach ($artikel as $item ){
$response = json_decode($item, true);
echo $response['name'];
}
?>

WordPress: get data from array in database

I have custom fields that are created dynamicaly. I get the data from those fields and store it into a database as an array with update_post_meta. It's stored as a serialised array in the database:
a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}
Now I need to get this array and echo it out on the website, so it looks something like: 4 children (1993,1994,1995,1996).
Here's the code I use now, but it doesn't work.
<?php
$children = get_post_custom_values('rbchildyear');
foreach ($children as $key => $value){
echo "$key => $value('rbchildyear')<br>";
}
?>
And thats what I get in the front office:
0 => a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}('rbchildyear')
So how can I do that?
Thank you!
use unserialize().
$children = unserialize('a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}');
print_r($children);
This will return array
If you use get_post_meta it will return an array of values (numerically indexed). Then you can loop through the array with a foreach.
$childYears = get_post_meta($post_id, "rbchildyear", true);
foreach($childYears AS $theYear)
{
$printThis .= $theYear.",";
}
print count($childYears)." children ( ".$printThis." )";

How do you create an array from variables derived from a foreach loop?

I'm certain this is VERY simple, but being new and not knowing what I'm doing I can't quite get it on my own.
I am trying to create an array of wordpress post ID's that is derived from a simple foreach loop.
Basically I have this as my code:
$omit_these_quizzes = array();
foreach ( $filtered_pass as $single_quiz ) {
$quiz_id_number = $single_quiz['quiz'];
$omit_these_quizzes[] = $quiz_id_number;
}
I would like to take each of the resulting $quiz_id_number 's and have then end up in array that looks like this:
$omit_these_quizzes = array(8195,8193);
However, I keep ending up with an array that only contains the variable from the very last foreach loop, instead of them all. What am I doing wrong?
Thanks!
Your code looks fine.But if you want alternative try this:
see here for in_array and array_push.
$omit_these_quizzes = array();
foreach ( $filtered_pass as $single_quiz )
{
$quiz_id_number = $single_quiz['quiz'];
if(!in_array($quiz_id_number ,$omit_these_quizzes))
{
array_push($omit_these_quizzes, $quiz_id_number);
}
}
hope it's help you.
This work?
$omit_these_quizzes = array();
foreach ( $filtered_pass as $single_quiz ) {
$quiz_id_number = $single_quiz['quiz'];
array_push($omit_these_quizzes, $quiz_id_number);
}
Looks like you are creating a new array in each loop, that's why you end up with an array containing just a single element...
Use:
$omit_these_quizzes = array();
foreach ( $filtered_pass as $single_quiz )
{
$quiz_id_number = $single_quiz['quiz'];
array_push($omit_these-quizzes, $quiz_id_number);
}
Your code is correct. Inspect your $filtered_pass variable by calling var_dump($filtered_pass); may be it contain only one subarray.

json_encode get values foreach object

Hello I can't figure out how to loop through this json encoded array and for each object, get all its values. I need each value as a variable for itself.
echo json_encode($formulars);
This is what i get when i echo it out
[{"project_name":"polle","type":"support","title":"vi","reason":"prover","solution":"igen","comments":"okay ","date_stamp":"2013-08-20 14:06:37","used_time":132},{"project_name":"dolla","type":"support","title":"lolol","reason":"skl","solution":"dskal","comments":"kflafda ","date_stamp":"2013-08-20 14:11:36","used_time":210},{"project_name":"polle","type":"fejl","title":"lol","reason":"aksdl","solution":"fdjks","comments":"djsks ","date_stamp":"2013-08-20 14:13:27","used_time":1230}]
I have tried this piece of code and I managed to get out the project_name from the first object and that's it:
foreach ($formulars as $current => $project_name) {
$project_name['project_name'];
}
So is there any way i can get all the variables for each object in my array instead of just the project_name?
Like this:
foreach ($formulars as $current){
$projectName = $current['project_name'];
$type = $current['type'];
$reason = $current['reason'];
}
Thanks in advance
Seems like you have an objects inside an array. So you will need to loop through the array and get each object. Just JSON_DECODE your encoded string like below.
Perhaps:
$data = json_decode($formulars,true);
/* Since it's only one object inside the array, you could just select element zero, but I wil loop*/
//You should now be able to do this
foreach ($data as $current){
$projectName = $current['project_name'];
$type = $current['type'];
$reason = $current['reason'];
}
The reason I loop is because there is a object inside an array(Javascript way I think).
Use json_decode to convert the json object to an array; then use foreach to loop through the array. That should work.
<?php
$arr_json = json_decode($formulars);
foreach($arr_json as $key => $value)
//Code to perform required actions
?>
This should give you some ideas.
Use json_decode (with TRUE for getting an associative array)to convert your JSON object to an associative array. After that, you can use a foreach loop to traverse through your multidimensional array and print the required values.
Code:
$json = json_decode($string, true);
foreach ($json as $key => $value) {
foreach($value as $key2 => $value2) {
echo $value2."\n";
}
}
Working Demo!

Select value out of array in PHP

Ok, so I have this in a JSON array (the output of retrievedData())
{
"device": {
"01AA02AB141208VV": {
"$version": -148598935,
"$timestamp": 1344382016000,
"serial_number": "01AA02AB141208VV"
}
}
}
However, I can't seem to select the serial number. I have tried what usually works, but I can't select it. This is assuming we don't already know the "01AA02AB141208VV".
$retrieved_data = retrieveData($array['userid'], $array['urls']['transport_url'], $array['access_token']);
$retrieved_data_array = json_decode($retrieved_data, true);
$serial_number = $retrieved_data_array['device'][0]['serial_number'];
Am I doing something wrong? I bet it's really simple, but I just cannot figure it out!
Thanks!
Unfortunately, it's not really simple. You're trying to find 42 Main St. when you don't know the city Main St. is located in. The only way to find the serial_number would be to loop over $retrieved_data_array with foreach until you find the value you want.
you can use key() function to access the keys of the associative array (in this case the '$retrieved_data_array['device']' array:
<?php
$data = '{"device": {"01AA02AB141208VV": {"$version": -148598935,"$timestamp": 1344382016000,"serial_number": "01AA02AB141208VV"}}}';
$retrieved_data_array = json_decode($data, true);
$serial_number = key($retrieved_data_array['device']);
reset($retrieved_data_array['device']);
print_r($serial_number);
print_r($retrieved_data_array['device'][$serial_number]);
?>
This will grab the serial numbers, assuming you have multiple items in the devices array:
$keys = array();
foreach( $retrieved_data_array['device'] as $key => $val ){
$keys[] = $key;
}
$serial = $keys[0];
This can be reduced if you know you only have one item in the array...

Categories