This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 3 years ago.
I have a question regarding on json.. I tried to get an api from other site and downloaded it as json file..I've already decoded this file using this code below..
$str = file_get_contents('../trelloApi.json');
$json = json_decode($str, true);
echo '<pre>' . print_r($json, true) . '</pre>';
From this image attached, how do I get or print the value of the [list] => Array, [board] => Array and [card] => Array?
Please help me :(
Looks like that the api return a array of arrays, then use foreach to iterate through the json_decode.
foreach ($json as $ticket) {
// if your $ticket['data'] is a StdClass, force to be array
$ticket['data'] = (array)$ticket['data'];
// now you can access your indexes
$list = $ticket['data']['list'];
$board = $ticket['data']['board'];
$card = $ticket['data']['card'];
}
If you don't like your $ticket['data'] as array, use as object instead $ticket['data']->list, $ticket['data']->board...
After json_decode you can this way retrieve 'list','board' and 'card' array data....May be help you..
$list=array();
$board=array();
$card=array();
foreach($json as $key => $value){
$list[]=$value[$key]['data']['list'];
$board[]=$value[$key]['data']['board'];
$card[]=$value[$key]['data']['card'];
}
echo "<pre>";
print_r($list);
print_r($board);
print_r($card);
You can access list array like below:
$list = $json['data']['list']
So access board array:
$board = $json['data']['board']
To access card array:
$card = $json['data']['card']
You get access for only 173 locaions array:
$list = $json[173]['data']['list'];
$board = $json[173]['data']['board'];
$card = $json[173]['data']['card'];
print_r($list);
print_r($board);
print_r($card);
you can get all of the array like
foreach ($json as $key => $value) {
$list[] = $value['data']['list'];
$board[] = $value['data']['board'];
$card[] = $value['data']['card'];
}
print_r($list);
print_r($board);
print_r($card);
Related
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
I have a JSON file containing a list of universities around the world. I want to get only specific universities where a field in the array matches what I need to select. The problem I face is that each university has it's own ID number which makes me unable to figure out how to iterate over the Array. The JSON file can be found on this GitHub repo.
The code that makes me convert the JSON file to an array:
<?php
$json = file_get_contents('universities_list.json');
$universityArray = json_decode($json, true);
print_r($universityArray);
?>
And a sample of what I get is:
[2942] => Array
(
[alpha_two_code] => EG
[country] => Egypt
[domain] => aast.edu
[name] => Arab Academy for Science & Technology
[web_page] => http://www.aast.edu/
)
[2943] => Array
(
[alpha_two_code] => EG
[country] => Egypt
[domain] => akhbaracademy.edu.eg
[name] => Akhbar El Yom Academy
[web_page] => http://www.akhbaracademy.edu.eg/
)
What is the best or appropriate way to print out only the universities with alpha_two_code == 'EG' or == 'Egypt' for example?
I read the documentation on foreach loop and the examples as well. But still can't get the logic to get what I mentioned above.
Check this return only a specific country
<?php
$json = file_get_contents('university.json');
$universityArray = json_decode($json, true);
universities= array()
for($i=0; $i< count($universityArray); $i++)
{
if($universityArray[$i]["country"] == "Morocco")
universitises[] = $universityArray[$i];
}
var_dump($universitises);
?>
You can use alpha_two_code as index.
$indexed = [];
foreach($universityArray as $university){
$index = $university['alpha_two_code'];
if(!isset($indexed[$index])){
$indexed[$index] = [];
}
$indexed[$index][] = $university;
}
Now you will have universities seperated by alpha_two_code which you can directly access.
print_r($indexed['EG']);
Now as per the best and appropriate part, you may want to cache $indexed. You can create a directory for universities and save JSON encoded $indexed there.
You need to read the manual.
Try this:
$names = array();
foreach($universityArray as $u) {
if($u['alpha_two_code'] == 'EG' || $u['country'] == 'Egypt'){
$names[] = $u['name'];
}
}
print_r($names);
you can use the array_filter http://php.net/manual/en/function.array-filter.php function here with a callback. You can then use array_column http://php.net/manual/en/function.array-column.phpto grab just the 'name' column.
$json = file_get_contents('https://github.com/Hipo/university-domains-list/blob/master/world_universities_and_domains.json');
$universityArray = json_decode($json, true);
$filterBy = 'EG';
$newArray = array_filter($universityArray, function ($var) use ($filterBy) {
return ($var['alpha_two_code'] == $filterBy);
});
print_r($newArray);
$names = array_column($newArray, 'name');
print_r($names);
I have a json like this:
[{"a":"1", "b":"2"},{"a":"4", "b":"5"},{"a":"15", "b":"2"}]
I want to get in php each row for update my database. I don't know the number of second level json are. Sometimes will be 1, sometimes 2 and sometimes more.
I thought, I could read it doing something like this:
$json = file_get_contents('php://input');
$json_post = json_decode($json, true);
$i = 0;
while(isset($json_post[$i])){
//Bla bla
$i++;
}
I have used many times json file in php but always, just one level. This is my first time with more than one.
But I can't. I know, because I checked, that in $json I have the complete json file.
You need to reference the subkey in your array:
$json = file_get_contents('php://input');
$json_post = json_decode($json, true);
$i = 0;
while(isset($json_post[$i])){
echo $json_post[$i]["a"];
// or
echo $json_post[$i][0];
$i++;
}
More docs can be found here: http://php.net/manual/en/language.types.array.php
And a similar question here: PHP reference specific key and value within multidimensional array
i'd use foreach:
foreach($json_post as $key => $value) {
echo $value;
}
$j = '[{"a":"1", "b":"2"},{"a":"4", "b":"5"},{"a":"15", "b":"2"}]';
$decoded = json_decode($j, true);
//var_dump($decoded);
foreach ($decoded as $key => $post) {
$valueOfA = $post['a'];
$valueOfB = $post['b'];
}
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!
I am trying to print the contents of a nested array, but it simply returns "Array" as a string yet will not iterate with a foreach loop. The arrays are coming from a mongodb find(). The dataset looks like this:
User
Post_Title
Post_Content[content1,content2,content3]
I am trying to get at the content1,2,3.
My current code looks like this:
$results = $collection->find($query);
foreach ($results as $doc)
{
echo $doc['title']; //this works
$content[] = $doc['content'];
print_r($content); //this prints "Array ( [0] => Array )"
foreach ($content as $item)
{
echo $item;
}
}
All this code does is print the Title, followed by Array ( [0] => Array ), followed by Array.
I feel quite stupid to not figure out something that seems so basic. Most posts on stack overflow refer to multidimensional associative arrays - in this case, the top level array is associative, but the content array is indexed.
I have also tried
foreach ($doc['content'] as $item)
But that gives
Warning: Invalid argument supplied for foreach()
I even tried iterating over the returned array again using a nested foreach, like the following:
foreach ($results as $doc)
{
echo $doc['title']; //this works
$content[] = $doc['content'];
print_r($content); //this prints "Array ( [0] => Array )"
foreach ($content as $item)
{
foreach ($item as $next_item)
{
echo $next_item;
}
echo $item;
}
}
The second foreach failed with an invalid argument..
Any thoughts would be greatly appreciated.
edit: perhaps it has something to do with how I am inserting the data to the DB. That code looks like this
$title = $_POST['list_title'];
$content[] = $_POST['list_content1'];
$content[] = $_POST['list_content2'];
$content[] = $_POST['list_content3'];
$object = new Creation();
$object->owner = "$username";
$object->title = "$title";
$object->content = "$content";
$object->insert();
Is this not the proper way to add an array as a property to a class?
The issue is some of array content is an array while other parts are strings. You should test for the sub content $doc being an array using is_array(). If it is, loop through the $doc like you would any other array, and if it isn't, you can echo the content (may need to test the content type before doing this if you're uncertain as to what content it can be)
The problem is in the code that you are saving data. You should replace the following line
$object->content = "$content";
with
$object->content = $content;
//go through each question
foreach($file_data as $value) {
//separate the string by pipes and place in variables
list($category, $question) = explode('|', $value);
//place in assoc array
$data = array($category => $question);
print_r($data);
}
This is not working as it replaces the value of data. How can I have it add an associative value each loop though? $file_data is an array of data that has a dynamic size.
You can simply do this
$data += array($category => $question);
If your're running on php 5.4+
$data += [$category => $question];
I think you want $data[$category] = $question;
Or in case you want an array that maps categories to array of questions:
$data = array();
foreach($file_data as $value) {
list($category, $question) = explode('|', $value, 2);
if(!isset($data[$category])) {
$data[$category] = array();
}
$data[$category][] = $question;
}
print_r($data);
Before for loop:
$data = array();
Then in your loop:
$data[] = array($catagory => $question);
I know this is an old question but you can use:
array_push($data, array($category => $question));
This will push the array onto the end of your current array. Or if you are just trying to add single values to the end of your array, not more arrays then you can use this:
array_push($data,$question);
For anyone that also need to add into 2d associative array, you can also use answer given above, and use the code like this
$data[$category]["test"] = $question
you can then call it (to test out the result by:
echo $data[$category]["test"];
which should print $question