JqGrid Data from URL - php

I am decoding JSON from an API:
$api = "http://xyzdomain.com/api";
$json = file_get_contents($api);
$array = json_decode($json,true);
print_r($array);
Here is the sample result of API objects and arrays.
Array
(
[status] => ok
[count] => 1
[meta] => Array
(
[count] => 1
)
[data] => Array
(
[accountid] => Array
(
[0] => Array
(
[all] => Array
(
[fans] => 16
[user post] => 333
[user Details] => xyz
)
[scorelist] => 1
[name] => John Doe 1
[timespent] => 5887
[nation] => usa
)
[1] => Array
(
[all] => Array
(
[fans] => 123
[user post] => 903
[user Details] => mno
)
[scorelist] => 6
[name] => John Doe 2
[timespent] => 1269
[nation] => usa
)
[2] => Array
(
[all] => Array
(
[fans] => 16
[user post] => 303
[user Details] => abc
)
[scorelist] => 1
[name] => John Doe 3
[timespent] => 9292
[nation] => ussr
)
[3] => Array
(
[all] => Array
(
[fans] => 16
[user post] => 333
[user Details] => jqr
)
[scorelist] => 1
[name] => John Doe 4
[timespent] => 75600
[nation] => usa
)
)
)
)
I used only three samples above, but it may go up to 500 or more.
I have basically two questions here:
I want to make a table using jqgrid or datatables or any other way it looks good.
How can I sum timespent where nation is, say, USA in above example?

$timespent_usa = 0;
foreach($array['data']['accountid'] as $account) {
if ($account['nation'] == 'usa') {
$timespent_usa += $account['timespent'];
}
}
echo $timespent_usa;
I'm not sure on how you plan on getting the data into datatables, you could just echo the data within each $account array within the foreach loop into <td> elements.

Related

Parse XML to Array with SimpleXML

I've that xml structure retrieving from device
<packet>
<info action="fiscalmemory" fiscalmemorysize="1048576" recordsize="464" fiscal="1" uniqueno="ABC12345678" nip="123-456-78-90" maxrecordscount="2144" recordscount="7" maxreportscount="1830" reportscount="4" resetmaxcount="200" resetcount="0" taxratesprglimit="30" taxratesprg="1" currencychangeprglimit="4" currencychangeprg="0" fiscalstartdate="dd-mm-yyyy hh:dd:ss" fiscalstopdate="dd-mm-yyyy hh:dd:ss" currencyname="PLN" />
<ptu name="A" bres="Nobi">123.23</ptu>
<ptu name="B">123.23</ptu>
<ptu name="D">8</ptu>
<sale>999.23</sale>
</packet>
simpleXml does't see ptu's attributes
$array = simplexml_load_string($xml);
print_r($array);
It prints
SimpleXMLElement Object
(
[info] => SimpleXMLElement Object
(
[#attributes] => Array
(
[action] => fiscalmemory
[fiscalmemorysize] => 1048576
[recordsize] => 464
[fiscal] => 1
[uniqueno] => ABC12345678
[nip] => 123-456-78-90
[maxrecordscount] => 2144
[recordscount] => 7
[maxreportscount] => 1830
[reportscount] => 4
[resetmaxcount] => 200
[resetcount] => 0
[taxratesprglimit] => 30
[taxratesprg] => 1
[currencychangeprglimit] => 4
[currencychangeprg] => 0
[fiscalstartdate] => dd-mm-yyyy hh:dd:ss
[fiscalstopdate] => dd-mm-yyyy hh:dd:ss
[currencyname] => PLN
)
)
[ptu] => Array
(
[0] => 123.23
[1] => 123.23
[2] => 8
)
[sale] => 999.23
)
As we can see ptu doesn't contain attributes :/
I also tried parse it with recursive function because children also may contain chilren but without success :/
Could anybody point to me why SimpleXML doesn't take ptu's attributes and also share any parsing function?
Thanks in advance.
edited
As regards Nigel Ren I made that function
function parseXMLtoArray($xml){
$x = simplexml_load_string($xml);
$result = [];
function parse($xml, &$res){
$res['name'] = $xml->getName();
$res['value'] = $xml->__toString();
foreach ($xml->attributes() as $k => $v){
$res['attr'][$k] = $v->__toString();
}
foreach($xml->children() as $child){
parse($child, $res['children'][]);
}
}
parse($x, $result);
return $result;
}
$resArray = parseXMLtoArray($rawXml);
print_r($resArray);
this returns such array
Array
(
[name] => packet
[value] =>
[attr] => Array
(
[crc] => BKJFKHKD54
)
[children] => Array
(
[0] => Array
(
[name] => info
[value] =>
[attr] => Array
(
[action] => fiscalmemory
[fiscalmemorysize] => 1048576
[recordsize] => 464
[fiscal] => 1
[uniqueno] => ABC12345678
[nip] => 123-456-78-90
[maxrecordscount] => 2144
[recordscount] => 7
[maxreportscount] => 1830
[reportscount] => 4
[resetmaxcount] => 200
[resetcount] => 0
[taxratesprglimit] => 30
[taxratesprg] => 1
[currencychangeprglimit] => 4
[currencychangeprg] => 0
[fiscalstartdate] => dd-mm-yyyy hh:dd:ss
[fiscalstopdate] => dd-mm-yyyy hh:dd:ss
[currencyname] => PLN
)
)
[1] => Array
(
[name] => ptu
[value] => 123.23
[attr] => Array
(
[name] => A
)
)
[2] => Array
(
[name] => ptu
[value] => 123.23
[attr] => Array
(
[name] => B
)
)
[3] => Array
(
[name] => ptu
[value] => 8
[attr] => Array
(
[name] => D
)
)
[4] => Array
(
[name] => sale
[value] => 999.23
)
)
)
Is this correct?
Thanks again Nigel
When loading with SimpleXML, using print_r() gives only an idea of the content and doesn't have the full content. If you want to see the full content then use ->asXML()...
$array = simplexml_load_string($xml);
echo $array->asXML();
To check the attributes of <ptu> element, (this just gives the first one)...
echo $array->ptu[0]['name'];
This uses ->ptu to get the <ptu> element and takes the first one [0] and then takes the name attribute using ['name'].

Php Group array by value and count group item [duplicate]

This question already has answers here:
How to count array with group by
(2 answers)
Closed 4 months ago.
I am creating a notification system. That results shown below returns all notifications for a particular user. I want to group the array by 'notify_id' and also count each item in a group.
Such that I'll have :
"Jack Bill is now following you", John Doe commented on your post 2",
"John Doe and 2 others commented on your post 1"
Array ( [0] =>
Array ( [id] => 1
[user_id] => 10
[type] => follow
[notify_id] => 13
[notify_date] => 1483444712
[firstname] => Jack
[surname] => Bill
[picture] => )
[1] =>
Array ( [id] => 10
[user_id] => 10
[type] => comment
[notify_id] => 2
[notify_date] => 1482159309
[firstname] => John
[surname] => Doe
[picture] => )
[2] =>
Array ( [id] => 8
[user_id] => 10
[type] => comment
[notify_id] => 1
[notify_date] => 1482159219
[firstname] => John
[surname] => Doe
[picture] => )
[3] =>
Array ( [id] => 6
[user_id] => 16
[type] => comment
[notify_id] => 1
[notify_date] => 1482159129
[firstname] => James
[surname] => Canon
[picture] => )
[4] =>
Array ( [id] => 5
[user_id] => 14
[type] => comment
[notify_id] => 1
[notify_date] => 1482159079
[firstname] => Sharon
[surname] => Abba
[picture] => ) )
You have two questions, I will try to answer both of them:
I want to group the array by 'notify_id'...
Assuming your array name is $a:
$return = array();
foreach($a as $val) {
if (!isset($return[$val['notify_id']])) {
$return[$val['notify_id']] = array();
}
$return[$val['notify_id']][] = $val;
}
print_r($return); // <-- Your array is grouped by notify_id
... and also count each item in a group.
Now you have your grouped by notify_id in $return so:
foreach($return as $k => $v) {
echo count($v) . ' values are present for notify #' . $k;
// It will display something like: 10 values are present for notify #1
}
Hope it will help, good luck!

PHP output an Array

i`ve an array with more arrays inside.
But how can i get a specific value from it ?
For example how can i output the first name "John" ?
I tried this but it doesn't work.
foreach($arr as $result) {
echo $result['CLIENTS']['FIRSTNAME'];
}
This is the < pre> output of the array
Array
(
[WHMCSAPI] => Array
(
[ACTION] => getclients
[RESULT] => success
[TOTALRESULTS] => 12
[STARTNUMBER] => 0
[NUMRETURNED] => 12
[CLIENTS] => Array
(
[CLIENT] => Array
(
[ID] => 14
[FIRSTNAME] => John
[LASTNAME] => Doe
[COMPANYNAME] => Muster Company
[EMAIL] => info#mustermann.de
[DATECREATED] => 2014-04-13
[GROUPID] => 0
[STATUS] => Active
)
)
)
)
The other answers & comments are almost right, but they didn't notice that you're iterating over the array.
Here's your code:
foreach($arr as $result) {
echo $result['CLIENTS']['FIRSTNAME'];
}
Inside the loop (this is important), $result is equal to:
Array
(
[ACTION] => getclients
[RESULT] => success
[TOTALRESULTS] => 12
[STARTNUMBER] => 0
[NUMRETURNED] => 12
[CLIENTS] => Array
(
[CLIENT] => Array
(
...
So to access the client name inside the loop, use this:
$firstname = $result["CLIENTS"]["CLIENT"]["FIRSTNAME"];
You're missing a couple levels of the array. Try $result['WHMCSAPI']['CLIENTS']['CLIENT']['FIRSTNAME'].

Codeigniter: Referencing a specific array index returned in model result

I'm still trying to wrap my head around passing db query results from a model back to controller and finally to a view. I seem to be getting the data to the right place, I'm just not sure how to best access the resulting array of objects in the view.
Specifically, I'm trying to query my db for the most recent 7 distinct dates that someone has submitted a link. I get back an array of dates, and then for each of those dates I do a query for all links submitted on that date and store the results in an array. Then in the view, for each of those distinct dates, I show a header (the date), immediately followed by the links associated with it.
The array that come from my distinct date query ($link_headers):
Array (
[0] => stdClass Object([added_date] => 2011-08-11)
[1] => stdClass Object([added_date] => 2011-05-03)
[2] => stdClass Object([added_date] => 2011-04-21)
[3] => stdClass Object([added_date] => 2011-04-10)
[4] => stdClass Object([added_date] => 2011-03-04)
[5] => stdClass Object([added_date] => 2011-02-28)
[6] => stdClass Object([added_date] => 2011-02-22)
)
The array that comes from my query for actual links submitted ($links_result):
Array
(
[0] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1178
[link_url] => http://www.amazon.com/Silicone-Rubber-CASSETTE-Design-IPHONE/dp/B004YDJWOY
[link_name] => Silicone Skin BLACK CASSETTE TAPE
[link_notes] => iPhone case... probably won't fit in my dock.
[added_date] => 2011-08-11
[flag_new] => 1
[rating] => 4
[public] => 1
)
)
[1] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1177
[link_url] => http://snorby.org/
[link_name] => Snorby - Snort front-end
[link_notes] =>
[added_date] => 2011-05-03
[flag_new] => 1
[rating] => 4
[public] => 1
)
)
[2] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1176
[link_url] => http://www.nytimes.com/2011/04/17/business/17excerpt.html?_r=4&pagewanted=1&ref=business
[link_name] => Corner Office - The 5 Habits of Highly Effective C.E.O.s
[link_notes] => Sounds a lot like what Nathanial said...
[added_date] => 2011-04-21
[flag_new] => 1
[rating] => 4
[public] => 1
)
)
[3] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1175
[link_url] => http://chezlarsson.com/myblog/2010/06/panduro-concrete-challenge-3.html
[link_name] => Concrete book-ends
[link_notes] => Cool look...
[added_date] => 2011-04-10
[flag_new] => 1
[rating] => 4
[public] => 1
)
[1] => stdClass Object
(
[user_id] => 2
[link_id] => 1174
[link_url] => http://themeforest.net/item/reciprocity-photo-blog-gallery/154590
[link_name] => Site Templates - Reciprocity - Photo Blog
[link_notes] =>
[added_date] => 2011-04-10
[flag_new] => 1
[rating] => 5
[public] => 1
)
)
[4] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1173
[link_url] => http://lifehacker.com/#!5771943/the-always-up+to+date-guide-to-jailbreaking-your-ios-device
[link_name] => The Always Up-to-Date Guide to Jailbreaking Your iOS Device
[link_notes] =>
[added_date] => 2011-03-04
[flag_new] => 1
[rating] => 4
[public] => 1
)
)
[5] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1172
[link_url] => http://lifehacker.com/#!5754463/how-to-jailbreak-your-ios-421-device
[link_name] => How to Jailbreak Your iOS 4.2.1 Device
[link_notes] =>
[added_date] => 2011-02-28
[flag_new] => 1
[rating] => 4
[public] => 1
)
)
[6] => Array
(
[0] => stdClass Object
(
[user_id] => 2
[link_id] => 1171
[link_url] => http://www.bitplumber.net/2010/10/a-cassandra-hardware-stack-dell-c1100s-ocz-vertex-2-ssds-with-sandforce-arista-7048s/
[link_name] => A Cassandra Hardware Stack
[link_notes] =>
[added_date] => 2011-02-22
[flag_new] => 1
[rating] => 3
[public] => 1
)
)
)
... all seems fine enough. But my problem comes from my view, where I'm trying to build the HTML as described above. A simplified view of the code I'm trying to get to work is as follows:
foreach ($link_headers as $header) {
echo "INDEX: ". $links_headers .", ADDED DATE: ". $header->added_date ."<BR>";
foreach ($links_result[$link_headers] as $result){
echo $result->added_date ."<BR>";
echo $result->link_name ."<BR><BR>";
}
}
So, I'm trying to use the index of the first one to tell my foreach loop which index of the second array to loop through and get the content. Clearly I'm misusing the $links_result[$link_headers] variable(s) but I left it in to show what I was trying to do.
Any help is very much appreciated!
Michael
I dont use CodeIgniter but whether within th framework or from PHP i would just grab it all in one go and then the issue with the indexes becomes moot:
SELECT * FROM model_table mt WHERE mt.added_date IN (
SELECT DISTINCT md.added_date from model_table md
ORDER BY md.added_date DESC
LIMIT 7
) ORDER BY mt.added_date DESC
That should get you an array of models ordered by date limted to the 7 most recent dates. So then its just a matter of choosing when to display a header:
$current = null;
foreach($links as $link) {
if($link->added_date !== $current) {
// show the header and set current to the current date
$current = $link->added_date;
echo 'HEADER: Added on ' . $current . '<br />';
}
echo $row->added_date ."<BR>";
echo $row->link_name ."<BR><BR>";
}

Trouble with displaying JSON array

could you please help me figure out why I'm getting "undefined" instead of the value.
As it is plain to see I'm having trouble getting the data from the array, in firebug I get this as a response....
{"status":"success",
"response":[
{"email":
{"email":"xxxxx#iing.mxl.uabc.mx",
"valid":"1",
"reason":null,
"confirmed_at":"0000-00-00 00:00:00",
"contact_email":"1",
"login_email":"1",
"users_id":"6375"},
"history":[
{"contactRole":"Non Classified Lead with History",
"contactProject":"2082",
"contactBrand":"B"},
{"contactRole":"co Author",
"contactProject":"32",
"contactBrand":"B"},
{"contactRole":"co Author",
"contactProject":"176",
"contactBrand":"B"},
{"contactRole":"co Author",
"contactProject":"582",
"contactBrand":"B"},
{"contactRole":"co Author",
"contactProject":"1858",
"contactBrand":"B"},
{"contactRole":"Author",
"contactProject":"12",
"contactBrand":"J"},
{"contactRole":"Editor",
"contactProject":"176",
"contactBrand":"B"}]},
{"email":
{"email":"xxxxx#hotmail.com",
"valid":"1",
"reason":null,
"confirmed_at":"0000-00-00 00:00:00",
"contact_email":"0",
"login_email":"0",
"users_id":"6375"},
"history":[]}]}
this is the code referring to my javascript file
http://pastebin.com/gPaEAKim
snapshot of the view that I'm getting.
Just to be on the safe side...this is the way the array looks like when I debug it from the controller
Array
(
[status] => success
[response] => Array
(
[0] => Array
(
[email] => Array
(
[email] => xxxxx#iing.mxl.uabc.mx
[valid] => 1
[reason] =>
[confirmed_at] => 0000-00-00 00:00:00
[contact_email] => 1
[login_email] => 1
[users_id] => 6375
)
[history] => Array
(
[0] => Array
(
[contactRole] => Non Classified Lead with History
[contactProject] => 2082
[contactBrand] => B
)
[1] => Array
(
[contactRole] => co Author
[contactProject] => 32
[contactBrand] => B
)
[2] => Array
(
[contactRole] => co Author
[contactProject] => 176
[contactBrand] => B
)
[3] => Array
(
[contactRole] => co Author
[contactProject] => 582
[contactBrand] => B
)
[4] => Array
(
[contactRole] => co Author
[contactProject] => 1858
[contactBrand] => B
)
[5] => Array
(
[contactRole] => Author
[contactProject] => 12
[contactBrand] => J
)
[6] => Array
(
[contactRole] => Editor
[contactProject] => 176
[contactBrand] => B
)
)
)
[1] => Array
(
[email] => Array
(
[email] => xxxxxxx#hotmail.com
[valid] => 1
[reason] =>
[confirmed_at] => 0000-00-00 00:00:00
[contact_email] => 0
[login_email] => 0
[users_id] => 6375
)
[history] => Array
(
)
)
)
)
If your data var in your JS code is the entirety of the JSON response, then you're working one level too high, and the inner loop is working 2 levels too high:
$.each(data['response'], function(i, email) {
^^^^^^^^^^^^--- missing this
$.each(email, function(ii, ...)) {
as your code stands now, the inner loop's email is overwriten your outer loop's as well.

Categories