Trying to loop and display a JSON file with PHP - php

I have a JSON file that has an array inside. I want to loop inside each element of the JSON and display it. I can succesfully do it but I want when using the foreach loop refer to the field like this: $value["pessoa_id"];
When I'm doing like this I get it to display but after displaying it gets a message: "Notice: Undefined index: nome", like it was trying to access it again.
This is the JSON file:
{"Clientes": {
"Pessoa": [
{"pessoa_id" : 1, "nome": "INDUSTRIAL JAVARI LTDA", "endereco": "ENGENHO SANTA TERESA"},
{"pessoa_id" : 2, "nome": "AGROISA-AGRO IND. TRAVESSIA S/A", "endereco": "FAZENDA TRAVESSIA S/N"}
],
"Clientes": [
{"cliente_id" : 1, "loja" : 1, "cliente" : 1, "tpcli": "J", "pontoref": ""},
{"cliente_id" : 2, "loja" : 1, "cliente" : 2, "tpcli": "J", "pontoref": ""}
]
}
}
And the php code:
$jsondata = file_get_contents("clitest.json");
$json = json_decode($jsondata, true);
foreach ($json as $key => $value){
foreach ($value as $key => $val){
foreach ($val as $key => $v){
echo $v["nome"] . " " . $v["endereco"];
echo "<br>";
}
}
}
I want to be able to in one foreach see if it's a "Pessoa" or "Clientes" and loop throught it by getting the fields by the name.

You also iterate over the 2nd array Clientes. You could access the array directly and only iterate over that data:
$jsondata = file_get_contents("clitest.json");
$json = json_decode($jsondata, true);
$pessoa = $json["Clientes"]["Pessoa"];
foreach ($pessoa as $key => $value){
echo $value["nome"] . " " . $value["endereco"];
echo "<br>";
}
Update:
If you need/want to loop over the whole data-set like you did in your question, you can check if you are in the correct element of the object and only than iterate and output the data.
$jsondata = file_get_contents("clitest.json");
$json = json_decode($jsondata, true);
foreach ($json as $key1 => $value){
if ($key1 == "Clientes") {
foreach ($value as $key2 => $val){
if ($key2 == "Pessoa") {
foreach ($val as $key3 => $v){
echo $v["nome"] . " " . $v["endereco"];
echo "<br>";
}
}
}
}
}

Related

Confused about how to loop through subArray

First of all I have searched for the similar threads on StackOverflow like this one
$myvar = array ("key_name" => array("tom", "an", "bob"),
"key_age" => array("1", "10", "12")
);
I have tried lot of things but I couldn't
foreach($myvar as $i){
foreach ($i as $key => $value) {
echo print_r($i);
}
I am trying to get "key_name" and loop through it
<?php
$myvar = array (
"key_name" => array("tom", "an", "bob"),
"key_age" => array("1", "10", "12")
);
foreach ($myvar['key_name'] as $value) {
echo $value;
}
Result:
tomanbob
https://3v4l.org/tEFvS
If you want to loop through both:
foreach ($myvar as $sub_array) {
foreach ($sub_array as $value) {
echo $value;
}
}
Result:
tomanbob11012
https://3v4l.org/cMFUh
Check out, http://php.net/manual/en/control-structures.foreach.php for info on using foreach
You can use array_walker. So you can do something like this :
array_walk($myvar,function($sub_items,$key){
echo "Key is >> " . $key . "\n";
foreach($sub_items as $item){
echo $item . "\n";
}
echo "------------ \n ";
});
Note:
I put an echo with a new line to understand how to implement that!

How to get json property name with php

So here's the thing, I get this json from a url ( in my context i get it from a url, but let's say here I write my json in a variable :
$file = '[
{"status": "5.4.1","email": "dddddd#exelcia-it.com"},
{"status": "5.4.1",, "email": "sksksksk#exelcia-it.com"}
]'
Then I do $json = json_decode($file,true);
And I want to get all the emails so I do :
foreach ($json as $key => $value) {
echo $value["email"]. "<br>";
}
But what I also need, is to return something like that from the loop (only for one property):
"email = dddddd#exelcia-it.com".
So I need to also get the name of the property but I can't figure this out.
I tried
foreach($json as $key => $propName){
echo $key.'<br>';
}
But I just get the index (0,1,...), not what I want.
Thanks!
You have to loop each json row, this should works:
$file = '[{"status": "5.4.1","email": "dddddd#exelcia-it.com"},{"status": "5.4.1", "email": "sksksksk#exelcia-it.com"}]';
$json = json_decode($file,true);
foreach($json as $row)
{
foreach($row as $key => $value)
{
echo "<b>".$key."</b>".':'.$value.'<br>';
}
}
Use this loop to get key and value pairs together.
foreach($data as $row)
{
foreach($row as $key => $val)
{
echo $key . ': ' . $val;
echo '<br>';
}
}
Ok thanks that's what I needed !
For me I just need the email properties and values, so I do :
foreach($json as $row)
{
foreach($row as $key => $value)
{
if($key=='email'){
echo "<b>".$key."</b>".':'.$value.'<br>';
}
}
}
Awesome ! thanks !

Issues with decoding json object

Thanks for your time in reading this post.
My php file is receiving a json object. But I am facing issues while decoding it.
My php code:
$data=$_POST['arg1'];
echo $data;
$json = json_decode($data,true);
echo $json;
$i = 1;
foreach($json as $key => $value) {
print "<h3>Name".$i." : " . $value . "</h3>";
$i++;
}
When I echo data results as below.
{
"SCI-2": {
"quantity": 2,
"id": "SCI-2",
"price": 280,
"cid": "ARTCOTSB"
}
}
When I echo $json, result is as it follows :
Array
Name1 : Array.
Please assist as i need tho access the cid and quantity values in the $data.
json_decode returns an array. And to print array you can use print_r or var_dump.
Now to access your values you can try :
$json["SCI-2"]["quantity"] for quantity and $json["SCI-2"]["cid"] for cid.
Demo : https://eval.in/522350
To access in foreach you need this :
foreach($json as $k) {
foreach($k as $key => $value) {
print "<h3>Name".$i." : " . $value . "</h3>";
}
}
Since you do not know the number of items in your object, use this:
$obj = json_decode($json);
After this, iterate the $obj variable and after that, inside the loop, use the foreach to get each property.
foreach($iteratedObject as $key => $value) {
//your stuff
}

iterate through json_encode array in PHP

i'm having problem on how to iterate in the array in json_encode.
I do ajax POST, in where i have a looping code that do "array push" in jQuery, something like this:
$(this).closest('tr.header').nextUntil('.header').each(function(){
i++;
var forms="<form method='POST'>"+$(this).html()+'</form>';
data.push($(forms).serializeArray());
});
So when i pass this to my controller/ other page, i do this:
$dataList = json_encode($this->input->post("form"));
echo $dataList ;
And the output is:
[
[{"name":"category_1", "values":"packages"},
{"name":"PK_1", "values": "1"}
],
[{"name":"category_2", "value":"products"},
{"name":"PK_2", "value": "3"}
]
]
I have tried to do :
foreach ($dataList as $data) {
echo $data . "\n";
}
But only give me error on foreach.
Thanks in advance.
Use json_decode()function to get your data as an array then foreach your data.
$a = '[
[{"name":"category_1", "values":"packages"},
{"name":"PK_1", "values": "1"}
],
[{"name":"category_2", "value":"products"},
{"name":"PK_2", "value": "3"}
]
]';
echo '<pre>';
$res = json_decode($a, true);
$newArr = [];
foreach($res as $data => $val)
{
foreach($val as $key2 => $val2)
{
$newArr[] = $val2;
}
}
foreach($newArr as $key => $val)
{
echo 'Name = ' . $val['name'] . ' Values = ' . $val['value'] . '<br/>';
}
Just decode the string and loop through the created array.
<?php
$a = '[
[{"name":"category_1", "values":"packages"},
{"name":"PK_1", "values": "1"}
],
[{"name":"category_2", "value":"products"},
{"name":"PK_2", "value": "3"}
]
]';
echo '<pre>';
$res = json_decode($a, true);
$newArr = array();
foreach($res as $data => $val)
{
foreach($val as $k=>$value){
$value=array_values($value);
echo 'Name => ' . $value[0] . ' Value => ' . $value[1] . '<br/>';
}
}
?>
for array output you need to decode it with json_decode()
here is sample code.
$encode_data = '[[{"name":"category_1", "values":"packages"},{"name":"PK_1", "values": "1"}],[{"name":"category_2", "value":"products"},{"name":"PK_2", "value": "3"}]]';
$dataAr = json_decode($encode_data , true);
foreach($dataAr as $data)
{
foreach($data as $value){
$value=array_values($value);
echo 'name => ' .$value[0] . ' value => ' .$value[1];
echo "<br>";
}
}

Using PHP to collect first three entries in JSON array

I've got this JSON array that contains data from a Google Analytics account. I want to collect the first three entries of this array and display using PHP. The problem is, I don't know the key to collect. Because it may vary. JSON looks like this:
"browsers": {
"Android Browser": 721,
"Chrome": 3362,
"Firefox": 912,
"Internet Explorer": 1776,
"Mozilla": 3,
"Opera": 190,
"Safari": 4501,
"Safari (in-app)": 284,
"Mozilla Compatible Agent": 82,
"Opera Mini": 7,
"Amazon Silk": 3,
"IE with Chrome Frame": 2,
"SeaMonkey": 1,
"KlappAppiPhone2": 8,
"Maxthon": 3
}
So I need to iterate through this array and print out both key and value.
I'm not that strong at PHP yet, and I thought I could just run a loop and echo out each value, something like this:
<?php
foreach($json->mobile as $row)
{
foreach($row as $key => $val)
{
echo $key . ': ' . $val;
echo '<br>';
}
}
?>
But I get an error Invalid argument supplied for foreach().
After googling that error, I found this snippet: if (is_array($values)) and I include that, nothing is echoed out. Is this not an array?
What am I doing wrong?
Follow this ...
Make use of json_decode()
You don't need of two foreach in this context
Set a flag so you could just display the first three values
The code
<?php
$json = json_decode($yourjsonstring);
$i=0;
foreach($json->mobile as $key => $val)
{
if($i<=2)
{
echo $key . ': ' . $val;
echo '<br>';
$i++;
}
}
<?php
$jsondata="your json data here";
$mobile=json_decode($jsondata);
foreach($mobile as $row)
{
foreach($row as $key => $val)
{
echo $key . ': ' . $val;
echo '<br>';
}
}
?>
Before send JSON string to foreach decode that with json_decode() function.
For example:
$json = {
"mobile": {
"iPad": 30,
"Lumia 920": 2,
"iPhone": 105,
"Nexus 4": 4,
"GT-I9100": 5,
"GT-I9300": 6,
"GT-N8000": 1,
"GT-P5100": 2
}
}
$decode = json_decode($json);
foreach($decode->mobile as $key => $value) {
echo $key . ': ' . $val;
echo '<br>';
}

Categories