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]);
Related
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);
I need to fetch value from an array .I need to fetch the value name,value,user_id from an given array
$inner_content='[{"name":"radio","value":"1","id":"1","user_id":"admin#gmail.com","web":"571710720","type":"poll_info","pg":"question_response"},{"name":"fav-color[]","value":"blue"}]'
$id='5'; //value given for expample.
$inner="select * from user_response where POLL_ID=$id";
$inner1=mysql_query($inner);
while($ifet=mysql_fetch_assoc($inner1))
{
$inner_content = $ifet['CONTENT_VALUES'];
$data1 = json_decode($inner_content);
$test1[]=array('name'=>$data1->name);
}
In JSON, square brackets denote an array, and curly braces denote an object. As you can see if you look carefully at $inner_content, it's an array containing a bunch of objects, so you need to index it.
$test1[] = array('name' => $data1[0]->name);
This just gets the name from the first object in the array. If you want to get all the names, you could use a foreach loop on $data1 (but only the first one has all the properties that you say you want).
$myArray = array();
for($i=0;i<2;$i++){
..
.. //get the content logic here
assign it to array
$myArray["item"]["content"] = $item_content;
}
echo json_encode($myArray);
The above code produced this result:
Which has an error because I didn't merge them.
I tried to merge like this:
$finalJson = array_merge($finalJson, $myArray);
but the output of echo $finalJson is one object instead of 3.
Update:
Your real problem is down to your use of array_merge on an associative array. The behaviour of array_merge is to reassign duplicate keys if they are associative (cf the docs):
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
And because $myArray is clearly using strings as keys, the values in $finalJson are being reassigned. What you need to do is either create unique keys on each iteration, or simply push the values of $myArray onto a numerically indexed $finalJson array (like I showed in my original answer below)
The problem is simply this:
$myArray["item"]["content"] = $item_content;
it's inside the loop, each time reassigning the value of $myArray["item"]["content"], and not adding it to the array. I suspect that what you wanted to do is add this at the bottom of your loop (for each new value of $myArray):
$finalJson[] = $myArray;
Then, on the next iteration, $myArray will be reassigned, and its new value will be appended to the $finalJson variable.
i have a tricky problem.
What i do.
I generate from the System Tables of Databases (DEV ,Test Prod setup) information for Tables, Vies trigger … with PHP and compare the results ti see teh differences with JavaScript.
Also I have a Documentation DB for additional business information which was installed only once on TEST DB.
Therfore I need to connect all four environments to get the data.
I use
if ($flag === 'i')
for information DB and
elseif ($flag === 's')
for system db‘s.
Result is $row_array and $info_array which must be combined and sendet back to Javascript.
$json_response = array_merge($rinfo, $rsql );
echo json_encode($json_response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
I try this merge in a different positions in the program.
First time in
elseif ($flag === 'i') {
result json:
[
{
"0": "ACT",……….
} ][ ]
second time after } //ifelse return also 2 arrays
[{"0":"ACT","1":"Tabelle Akten","2":"hh","3":null,"4":null,"5":"UCC","6":"Y","7":"Reload Data in Test","8":"y","9":"delete all older tha","10":"n","11":" ","12":"y","13":" ","14":"o","15":"y","16":"o","17":"y","18":"y","19":"Diese tabelle speichert die Acten Verweise","20":"Gert Dorn","21":1570254359,"TDESCRIPTION":"n","TTYPE":" ","TREC_ESTIM":"y","TREC_GROWTH":" ","TDOMAIN":"o","TREL_TYPE":"y","TREL_RULES":"o","THOUSEKEEPING":"y","THOUSE_RULES":"y","TCID":"Diese tabelle speichert die Acten Verweise","TCID_RULES":"Gert Dorn","TUSE_UCC":1570254359,"TUSE_DWH":"","TUSE_ODS":"","TUSE_CWF":"","TUSE_IWF":"","TUSE_OWF":"","TUSE_DEP_MANAGER":"","TENTITY_DESCRIPTION":"","TOWNER":""
,"TTIMESTAMP":""**}][{**"0":"ACT","1":"DB2INST1"
,"2":"USERSPACE1","3":null,"4":"2018-11-21 16:43:20.066567","5":"2018-12-07 10:12:10.255759","6":null,"7":"2020-03-26","8":"2018-11-21 16:43:20.343258","9":3,"NAME":"ACT","CREATOR":"DB2INST1","TBSPACE":"USERSPACE1","REMARKS":"","CTIME":"2018-11-21 16:43:20.066567","STATS_TIME":"2018-12-07 10:12:10.255759","STATISTICS_PROFILE":"","LASTUSED":"2020-03-26","ALTER_TIME":"2018-11-21 16:43:20.343258","COLCOUNT":3}]
The program code and result you can download at
http://dmdg.io/dmdg.zip
Hope you can help Kind regards gert
Did you consider using array_push?
array_push is always preferred than myArray[] = $value
I am trying to get json data from the Statcounter API.
I have the following:
$query = makeQuery("2292634", "demo_user", "statcounter", "visitor", "");
echo $query . "<br>";
$response = file_get_contents($query, true);
$data = json_decode($response, true);
echo $data['sc_data']['log_visits'];
I know the query is correct, and I know the $response is filled with unformatted json. The trouble is accessing the array and pulling the values out.
Here are the first couple lines of the unformatted json it is giving me.
This link will only work for 15 minutes, I can generate a new one if you would like to see the raw json.
http://api.statcounter.com/stats/?vn=3&s=visitor&pi=2292634&t=1398791335&u=demo_user&sha1=c6cdfd6c84227801c6ca758c17252712e3f76514
{"#attributes":{"status":"ok"},"sc_data":[{"log_visits":"1","entries_in_visit":"2","entry_t":"2014-04-29 17:57:33","entry_url":"http:\/\/www.guitar-online.com\/en\/","entry_title":"Learn how to play the guitar: tutorials, guitar
Obviously I am not accessing the array in the correct way...but I haven't found the syntax to make it work YET!
Thank you for your help.
Looking at your data, sc_data is an array containing nested JSON objects so you should be able to iterate over that array to read the data like you want:
echo $data['sc_data'][0]['log_visits'];
The code above will access the first element of the array sc_data and print the value of log_visits
When you have {"field":['a','b','c']} in JSON, you would access 'a' as field[0].
The elements of the array can be any valid value, i.e.
string
number
object
array
true
false
null
In your case it is objects and you access that object the same way you would access any other array element - by the index number (JSON doesn't have associative array of type "key" => "value")
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.