I have a json data like
{"Nepal":"1","India":"3","Pakistan":"2","America":"25","Bangaladesh":"23"}
Now what I want is to print and access data from last to top
to print like this using PHP
Bangaladesh 23
America 25
Pakistan 2
India 3
Nepal 1
Thank you in advance..
you can do reverse loop like this using list.length. Code depends upon the language you are using.
for(var i=list.length-1;i>=0;i--){
//your printing here
}
As Ruchan mentioned, iterating over your JSON Array object in reverse is a solution. Here is a snippet for PHP
//Decode the JSON
$array = json_decode('[{"Nepal":"1","India":"3","Pakistan":"2","America":"25","Bangaladesh":"23"}]',false); //Note: Second parameter is a boolean indicating if the resulting array should be associative or not
//Get the length of the Array
$length = count($array);
//Iterate over the array from the last index to the first (ie, length-1 to 0)
while($length) {
echo sprintf("<p>%s</p>", $array[--$length]);
}
Related
I have the following JSON:
[
{
"0":"2019-08-31",
"1":"Bank Exp.",
"2":"AED",
"3":"30",
"4":"",
"5":"BANK FEE 10"
},
{
"0":"2019-08-31",
"1":"Inventory",
"2":"AED",
"3":"122",
"4":"",
"5":"DEPOSIT 10000"
},
{
"0":"2019-08-31",
"1":"Petty Cash",
"2":"AED",
"3":"4999",
"4":"",
"5":"DEPOSIT 10000"
}
]
I am trying to Count the number of elements or columns in the Json. The result should be 6.
I have tried with echo count($data_array); (or sizeof) result is 3 (number of rows). How can I count the "columns" in this Json, taking into account that I must set as number of column the Max number of column a specific row has?
Do I have to use a loop to count or can I do it with a single instruction?
Assuming that some var $json contains the JSON code you have above, you should be aware that the following code will result in an array of objects of type stdClass:
$data_array = json_decode($json);
So $data_array is in fact an array, but it contains objects. As you pointed out, this will return the number of rows in your JSON:
echo sizeof($data_array);
Clearly, the number of columns is not the number of rows. If you want to know the number of columns then you'll need to check one or more rows/objects/elements of your $data_array var. It's expedient to just look at the first element:
$col_count = sizeof($data_array[0]);
HOWEVER, this is going to cause an E_WARNING if $data_array's elements are objects of type stdClass:
PHP Warning: sizeof(): Parameter must be an array or an object that implements Countable in /tmp/foo.php on line 33
You could optionally use the second parameter of the json_decode function which will force PHP to decode every curly bracketed object in your JSON code as an associative array instead of stdClass objects:
$data_array = json_decode($json, TRUE);
$col_count = sizeof($data_array[0]);
This yields a $col_count value of6 which is the correct for the first object in your array. You should consider that later elements in $data_array may have either more or fewer columns, depending on the structure of your data. If you are sure that all elements will have the same number of columns, this is adequate, but if you have messy data, you may need to check every element of your data array to see what the true number of columns is:
$data_array = json_decode($json, TRUE);
$col_count = 0;
foreach($data_array as $row) {
$col_count = max($col_count, sizeof($row));
}
var_dump($col_count);
This will yield a $col_count value which reflects the maximum number of columns encountered in any element of your JSON. Clearly, there may be performance considerations if your JSON contains a large number of elements. It all depends on your JSON data and the nature of your application.
EDIT:
Instead of an explicit foreach loop, I think you can get away with this, but it will still require PHP to loop through your data structure. That said, it'll probably be faster:
$max_col_count = max(array_map("count", $data_array));
count($data_array) counts the number of elements in an array. In your case, is 3. But your array is multidimensional (matrix). So you need to count on some index to get the number of columns on that position:
<?php
echo count($data_array[0]);
I have a script that loops through and retrieves some specified values and adds them to a php array. I then have it return the value to this script:
//Returns the php array to loop through
$test_list= $db->DatabaseRequest($testing);
//Loops through the $test_list array and retrieves a row for each value
foreach ($test_list as $id => $test) {
$getList = $db->getTest($test['id']);
$id_export[] = $getList ;
}
print(json_encode($id_export));
This returns a JSON value of:
[[{"id":1,"amount":2,"type":"0"}], [{"id":2,"amount":25,"type":"0"}]]
This is causing problems when I try to parse the data onto my android App. The result needs to be something like this:
[{"id":1,"amount":2,"type":"0"}, {"id":2,"amount":25,"type":"0"}]
I realize that the loop is adding the array into another array. My question is how can I loop through a php array and put or keep all of those values into an array and output them in the JSON format above?
of course I think $getList contains an array you database's columns,
use
$id_export[] = $getList[0]
Maybe can do some checks to verify if your $getList array is effectively 1 size
$db->getTest() seems to be returning an array of a single object, maybe more, which you are then adding to a new array. Try one of the following:
If there will only ever be one row, just get the 0 index (the simplest):
$id_export[] = $db->getTest($test['id'])[0];
Or get the current array item:
$getList = $db->getTest($test['id']);
$id_export[] = current($getList); //optionally reset()
If there may be more than one row, merge them (probably a better and safer idea regardless):
$getList = $db->getTest($test['id']);
$id_export = array_merge((array)$id_export, $getList);
Confusing title, the basics are that I'm saving a fully sorted and ordered multidimensional array from a script and into MySQL. I then, on another page, pull it from the database and unserialize it, and then proceed to print it out with this,
$s = "SELECT * FROM gator_historical_data WHERE channelid = '{$chanid}'";
$r = $link->query($s);
$comboarray = array();
while ($row = mysqli_fetch_assoc($r)) {
$comboarray[] = unserialize($row['dataarray']);
}
foreach ($comboarray as $item) {
$desc = $item['content']['description'];
$title = $item['content']['title'];
$datetime = $item['datetime'];
// ... ^^^ problems getting array data
}
The problem is that it doesn't take the full array from MySQL, only the first entry and thus only prints the first 'array'. So where the returned value from dataarray looks like this (var_dump): http://pastebin.com/raw.php?i=Z0jy55sM the data stored into the unserialized $comboarray only looks like this (var_dump): http://pastebin.com/raw.php?i=Ycwwa924
TL;DR: Pulling a serialized multidimensional array from a database, unserializing and it loses all arrays after the first one.
Any ideas what to do?
The string you've got is a serialized string plus something more at the end that is also a serialized string again and again:
a:3:{s:6:"source";s:25:"World news | The Guardian";s:8:"datetime ...
... story01.htm";}}a:3:{s:6:"source";s:16:"BBC News - World";
^^^
This format is not supported by PHP unserialize, it will only unserialize the first chunk and drop everything at the end.
Instead create one array, serialize it and store that result into the database.
Alternatively you can try to recover for the moment by un-chunking the string, however in case the paste was done right, there are more issues. But on the other hand the paste obvious isn't the done fully correct.
I have a JSONArray generated in java and I post it to one of my PHP files where it's saved to a file. From there it gets read and I need to generate a chart based on this data. All I need is to convert my raw JSON which has values I don't need, into a simply php array.
[{"id":1,"timestamp":"1363135091","reward":1200,"player":"Orangeguy24","address":"108.28.239.167","service":"MC-Index"},{"id":2,"timestamp":"1363135091","reward":1200,"player":"Orangeguy24","address":"108.28.239.167","service":"MC-Index"}]
Is an example of 2 elements inside my JSON array. What I need todo is filter those values into arrays accordingly.
For example get how many votes a 'player' has, I need to add up how ever many elements are in the JSONArray, because 1 element is 1 vote (the id is primary auto-increment in my mysql DB, not located on my webserver)
I'd like the array to be to [player, votes] so when I echo the array it will be easily parsed by the google chart tools I'm using. I've spent the last 5 hours working on this and I've been stuck, thanks for any help!
To decode the JSON into a php array, you can do:
$json_array = json_decode($raw_json);
Then, to get the number of votes for each player out of the array:
$player_votes = array_reduce($json_array,
function($v, $item) {
if(!array_key_exists($item->player, $v))
$v[$item->player] = 1;
else
$v[$item->player] = 1 + $v[$item->player];
return $v;
}, array());
If I understand your question correctly, this will work.
EDIT: Updated the second code snippet
Try this :
$str = '[{"id":1,"timestamp":"1363135091","reward":1200,"player":"Orangeguy24","address":"108.28.239.167","service":"MC-Index"},{"id":2,"timestamp":"1363135091","reward":1200,"player":"Orangeguy24","address":"108.28.239.167","service":"MC-Index"}]';
$res = array();
foreach(json_decode($str,true) as $val){
if(array_key_exists($val['player'],$res)){
$res[$val['player']] = $res[$val['player']]+1;
}
else{
$res[$val['player']] = 1;
}
}
echo "<pre>";
print_r($res);
Output :
Array
(
[Orangeguy24] => 2
)
I am trying to change the class of a list of elements based on information in a DB. I figure the easy way was via an array. I build the array on the php side as follows.
$setClassResult = array();
while($row = mysql_fetch_array( $result ))
{
$setClassResult= array_push_assoc($setClassResult, $row['item_id'], $row['parent']);
}
echo json_encode(array($setClassResult));
break;
which give me....
[{"830":"0","734":"830","733":"830","732":"830","735":"830","737":"830","736":"830","738":"830","739":"830","740":"830","741":"830","742":"830","872":"0","869":"872","868":"872","880":"872","964":"872"}]
to decode and change the elements I use.....
$.each(data, function(key, val) {
$("#recordsArray_"+key).toggleClass(val);
alert(key+" "+val);
});
The alert happens once with 0[object,Object] Is this because of the way I created the array? The first thing I notice wrong is the [ and ] around the JSON.
No need to add extra array, try with :
echo json_encode($setClassResult);
Your result is in array of object format:
[{"830":"0","734":"830","733":"830","732":"830","735":"830","737":"830","736":"830","738":"830","739":"830","740":"830","741":"830","742":"830","872":"0","869":"872","868":"872","880":"872","964":"872"}]
So when you iterate, it iterates through array first & says key is 0 & value is an object.so, if you later iterate through value which is an object, you will get it
or as soju if u dont require to store it in array of objects but a single object & iterate once.