Using PHP to collect first three entries in JSON array - php

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>';
}

Related

Trying to loop and display a JSON file with 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>";
}
}
}
}
}

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
}

foreach doesn't print altered array properly

I am trying to print an array using foreach and while printing, if a certain $key comes up, I want to make changes to the array. Problem is, even though the array gets changed, the changes do not get printed.
In the example below, you will find:
function I use to change the array;
an array first printed with no changed;
then echo print-out in with changes during the process - all using foreach;
another print-out of the same table, but this time with changes.
<?php
function insert_before_key($array, $key, $data = NULL){
if (($offset = array_search($key, array_keys($array))) === false){
$offset = count($array);
}
return array_merge(array_slice($array, 0, $offset), (array) $data, array_slice($array, $offset));
}
$array = array(
"no_color" => "blank",
"color1" => "red",
"color2" => "green",
"color3" => "blue",
);
echo "<pre>";
print_r($array);
echo "</pre>";
foreach ($array as $key => $value) {
echo $key . ": " . $value . "<br />";
if ($key === "color1"){
$array = insert_before_key($array, "color2", array("color1.5" => "yellow"));
}
}
echo "<pre>";
print_r($array);
echo "</pre>";
echo "<br />";
?>
Note that the new $key is to jump in AFTER current $key, so I would expect it to come up.
Any idea why this happens ?
EDIT:
Played a bit more with foreach and I think it must be caching the keys or something...
<?php
$test_array = array(0,1,2,3,4,5,6,7,8,9);
foreach ($test_array as $key => $value) {
if ($key === 5){$test_array[7] = $test_array[7]+1;}
echo $key . ": " . $value . "<br />";
}
print_r($test_array);
?>
The above will display UNCHANGED echo, but CHANGED print_r.
From the manual: "As foreach relies on the internal array pointer, changing it within the loop may lead to unexpected behavior." http://php.net/manual/en/control-structures.foreach.php
You shouldn't modify an array you're looping over.
So during iteration you are trying to change the value of the item being iterated
foreach($array ...)
{
change $array
}
Use a copy of $array inside the iteration
$array2 = $array
foreach($array ...)
{
change $array2
}
I'd keep it simple. Something tells me however that you're fixing effects of a problem here and not its source.
$array = array(
"no_color" => "blank",
"color1" => "red",
"color2" => "green",
"color3" => "blue",
);
$temp_array = array();
foreach ($array as $key => $value) {
$temp_array[$key] = $value;
echo $key . ": " . $value . "<br />";
if ($key == 'color1') {
$key_add = 'color1.5';
$value_add = 'yellow';
$temp_array[$key_add] = $value_add;
echo $key_add . ": " . $value_add . "<br />";
}
}
$array = $temp_array;

PHP - How to Loop through JSON array with fields starting with "$"

I have been trying to workout how to loop through and output the contents of a json file where field names start with "$" and keep getting an Undefined variable error message
Here is an example of the json file example (taken from https://mixpanel.com/help/reference/webhooks):
[
{
"$distinct_id":"13b20239a29335",
"$properties":{
"$region":"California",
"$email":"harry.q.bovik#andrew.cmu.edu",
"$last_name":"Bovik",
"$created":"2012-11-20T15:26:16",
"$country_code":"US",
"$first_name":"Harry",
"Referring Domain":"news.ycombinator.com",
"$city":"Los Angeles",
"Last Seen":"2012-11-20T15:26:17",
"Referring URL":"http://news.ycombinator.com/",
"$last_seen":"2012-11-20T15:26:19",
}
},
{
"$distinct_id":"13a00df8730412",
"$properties":{
"$region":"California",
"$email":"anna.lytics#mixpanel.com",
"$last_name":"Lytics",
"$created":"2012-11-20T15:25:38",
"$country_code":"US",
"$first_name":"Anna",
"Referring Domain":"www.quora.com",
"$city":"Mountain View",
"Last Seen":"2012-11-20T15:25:39",
"Referring URL":"http://www.quora.com/What-...",
"$last_seen":"2012-11-20T15:25:42",
}
}
]
I am testing with a static string just to try and get things working. Here is my test code...
<?php
$input = '[{"$distinct_id":"13b20239a29335","$properties":"dddd"}]';
$jsonObj = json_decode($input, true);
foreach ($jsonObj as $item) {
foreach ($item as $rec) {
echo '<br>';
$my_id = $rec->$distinct_id;
echo($my_id);
$my_id = $rec->$properties;
echo($my_id);
}
echo '<br>';
}
?>
Any help would be appreciated.
Noob!
UPDATE: Musa gave this example which works for the single level json:
foreach ($jsonObj as $item) {
echo '<br>';
$my_id = $item->{'$distinct_id'};
echo($my_id);
$my_id = $item->{'$properties'};
echo($my_id);
echo '<br>';
}
How can this then be adapted to read and output all elements of the bigger multi-level json file?
Use Curly bracket notation
$object->{'$property'};
Edit
foreach ($jsonObj as $item) {
echo '<br>';
$my_id = $item->{'$distinct_id'};
echo($my_id);
foreach ($item->{'$properties'} as $my_prop => $value){
echo("$my_prop => $value");
}
echo '<br>';
}
http://codepad.org/1cudZqlu
With the nested loop you're iterating the properties $distinct_id and $properties so $rec is actually a string and not an object.
Also your json is invalid as it has trailing , in the $properties field.

Categories