I been playing around with google chart for my project, and somehow I'm still cant figure out displaying multidimensional array (from database).
print_r() output:
Array
(
[0] => Array
(
[year] => 2000
[value] => 2766
[typeName] => Oil
)
[1] => Array
(
[year] => 2000
[value] => 3098
[typeName] => Gas
)
[2] => Array
(
[year] => 2000
[value] => 269814
[typeName] => Coal
)
[3] => Array
(
[year] => 1999
[value] => 2836
[typeName] => Oil
)
[4] => Array
(
[year] => 1999
[value] => 3150
[typeName] => Gas
)
[5] => Array
(
[year] => 1999
[value] => 257561
[typeName] => Coal
)
);
as google chart required data format, I want it to be something like this:
['Year' , 'Oil', 'Gas', 'Coal']
["2000", 2766, 3098, 269814],
["1999" 2836, 3150, 257561]
Can someone help me how to play around with the multidimensional?
Thanks!
You shuld convert this data into json. Just parse in this way to get the desired structure O(n)
$headers = array("year" => 0, "oil" => 1, "gas" => 2, "coal" => 3);
$response[] = array_map("ucfirst",array_keys($headers));
foreach($orig_array as $k => $item) {
$temp_data[$item['year']][0] = (string) $item['year'];
$temp_data[$item['year']][$headers[$item['typeName']]] = $item['value'];
if(4==count($temp_data[$item['year']])) $response[] = $temp_data[$item['year']];
}
$json_data = json_encode($response);
echo($json_data);
Related
I am exporting data from mysqli to google firebase DB. In firebase table one of the column named siteGeoCode (latitude and longitude) having values like [17.426083,78.439241] in array format. But in mysqli table two separate columns are there for latitude and longitude. I am trying to fetch records like below and converting those to array format.
$emp_array = array();
$sel_query = "select companyId,countryCode,createdBy,createdDat,`latitude`,`longitude`,siteName,`status` from customers limit 0,3";
$res = mysqli_query($mysqliConn,$sel_query);
while($sel_row = mysqli_fetch_assoc($res))
{
$emp_array[] = $sel_row;
$lat_array['siteGeoCode'][0] = $sel_row['latitude'];
$lat_array['siteGeoCode'][1] = $sel_row['longitude'];
array_push($emp_array,$lat_array);
}
// output
[0] => Array
(
[companyId] => iArwfGLC1lE6x3lO24cb
[countryCode] => 91
[createdBy] => X54P6gVJ7dA4Fi2fjEmc
[createdDate] => 2019-08-20 00:58:08
[latitude] => 15.6070347
[longitude] => 79.6146273
[siteName] => Ongole
[status] => 1
)
[1] => Array
(
[siteGeoCode] => Array
(
[0] => 15.6070347
[1] => 79.6146273
)
)
[2] => Array
(
[companyId] => YPbhSLWQfAR6ThhszSAf
[countryCode] => 91
[createdBy] => iArwfGLC1lE6x3lO24cb
[createdDate] => 2019-09-10 22:37:08
[latitude] =>
[longitude] =>
[siteName] => Madhap
[status] =>
)
[3] => Array
(
[siteGeoCode] => Array
(
[0] =>
[1] =>
)
)
but my desired output should be like below
[0] => Array
(
[companyId] => iArwfGLC1lE6x3lO24cb
[countryCode] => 91
[createdBy] => X54P6gVJ7dA4Fi2fjEmc
[createdDate] => 2019-08-20 00:58:08
[siteGeoPoint] => Array
(
[0] => 15.6070347
[1] => 79.6146273
)
[siteName] => Ongole
[status] => 1
)
[1] => Array
(
[companyId] => YPbhSLWQfAR6ThhszSAf
[countryCode] => 91
[createdBy] => iArwfGLC1lE6x3lO24cb
[createdDate] => 2019-09-10 22:37:08
[siteGeoPoint] => Array
(
[0] =>
[1] =>
)
[siteName] => Madhap
[status] =>
)
How can I achieve this ? Any help would be greatly appreciated. Thanks in advance
If you are wanting to place the result of the latitude/longitude columns into the result grouped, do the manipulations to the row, then add it to your result set, abit like below.
$result = [];
while ($row = mysqli_fetch_assoc($res)) {
// group geo
$row['siteGeoCode'] = [
$row['latitude'],
$row['longitude']
];
// unset uneeded
unset($row['latitude'], $row['longitude']);
// place in result
$result[] = $row;
}
You can use following code.
$output_array = array();
while($sel_row = mysqli_fetch_assoc($res)) {
$output_array[] = array(
'companyId' => $sel_row['companyId'],
'countryCode' => $sel_row['countryCode'],
'createdBy' => $sel_row['createdBy'],
'createdDate' => $sel_row['createdDate'],
'siteGeoPoint' => array($sel_row['latitude'], $sel_row['longitude']),
'siteName' => $sel_row['siteName'],
'status' => $sel_row['status'],
);
}
print_r($output_array);
you can see the difference you've used the array and I did. From you output I guess you've print different arrays.
Hope the code get you desire result!
I want to group results by month, to be precise Sum of total prices for each month, but i don't understand how i can divide months, then Sum price for each month.
This is required for morris chart like this
$data2[] = array(
'y' => $month,
'a' => price,
'b' => ''
);
I was using before query to get this results and was a easy way to do it, but now with code is different story.
Any help with explanation of how each segment of code is work will be so nice, so i can avoid problems like this one in future.
I need something like this :
$month = [May, June];
$price = [Sum of all prices for May, Sum of all prices for June];
This is a code :
$monthsArray = array();
// get all dates in array
foreach ($array as $key) {
// convert dates to short format, month-year -> Jun-18
$monthsArray[] = date('M-y', strtotime($key['time']));
}
$months = array();
foreach ($monthsArray as $date) {
$mon = substr($date, 0, 6);
if (!in_array($mon, $months)) array_push($months, $mon);
}
foreach ($months as $m) {
// final array for chart
$data2[] = array('y'=>$m, 'a'=>'', 'b'=>'');
}
$morris = json_encode($data2);
This is array i have
Array
(
[0] => Array
(
[price] => -1835.25
[time] => 2018-05-29 16:53:38
)
[1] => Array
(
[price] => -1743.52
[time] => 2018-05-29 16:53:39
)
[2] => Array
(
[price] => -4445.55
[time] => 2018-05-31 13:21:04
)
[3] => Array
(
[price] => -34647.04
[time] => 2018-05-31 18:29:43
)
[4] => Array
(
[price] => 16888.41
[time] => 2018-06-01 15:05:24
)
[5] => Array
(
[price] => 14369.05
[time] => 2018-06-07 14:44:21
)
[6] => Array
(
[price] => -49579.69
[time] => 2018-06-11 09:14:42
)
[7] => Array
(
[price] => -33300.94
[time] => 2018-06-08 23:50:29
)
[8] => Array
(
[price] => 4413.21
[time] => 2018-06-12 07:15:52
)
[9] => Array
(
[price] => 2724.69
[time] => 2018-06-12 07:15:46
)
[10] => Array
(
[price] => 10224.03
[time] => 2018-06-08 14:00:13
)
[11] => Array
(
[price] => -797.92
[time] => 2018-06-08 13:54:08
)
[12] => Array
(
[price] => -25157.34
[time] => 2018-06-11 11:31:31
)
[13] => Array
(
[price] => 2701.6
[time] => 2018-06-11 14:32:08
)
[14] => Array
(
[price] => 2038.92
[time] => 2018-06-12 07:15:48
)
[15] => Array
(
[price] => -10541.58
[time] => 2018-06-15 10:35:58
)
)
EDIT:
I manage to group months as you can see in updated code and now i am getting only 2 results as i should be, now its just a issue with SUM of data for each month.
This is what i am getting in console
0: {y: "May-18", a: "", b: ""}
1: {y: "Jun-18", a: "", b: ""}
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'].
I have json return string like given below. I want to extract cancellation Policy list of objects like cutoff Time and refund In Percentage. I tried using for-loop but it didn't help me. Can you please help me on extracting this.
Array (
[apiStatus] => Array ( [success] => 1 [message] => SUCCESS ) <br>
[apiAvailableBuses] => Array ( <br>
[0] => Array ( [droppingPoints] => [availableSeats] => 41 <br>[partialCancellationAllowed] => [arrivalTime] => 08:00 AM <br>
[cancellationPolicy] => [<br>
{"cutoffTime":"1","refundInPercentage":"10"},<br>
{"cutoffTime":"2","refundInPercentage":"50"},<br>
{"cutoffTime":"4","refundInPercentage":"90"}<br>
] <br>
[boardingPoints] => Array ( [0] => Array ( [time] => 09:00PM [location] => Ameerpet,|Jeans Corner 9687452130 [id] => 6 ) [1] => Array ( [time] => 09:15PM [location] => S.R Nagar,S.R Nagar [id] => 2224 ) [2] => Array ( [time] => 09:10PM [location] => Kondapur,Toyota Show room [id] => 2244 ) ) [operatorName] => Deepak Travels [departureTime] => 9:00 PM [mTicketAllowed] => [idProofRequired] => [serviceId] => 6622 [fare] => 800 [busType] => 2+1 Hi-Tech Non A/c [routeScheduleId] => 6622 [commPCT] => 0 [operatorId] => 213 [inventoryType] => 0 ) <br>
[1] => Array ( [droppingPoints] => [availableSeats] => 41 [partialCancellationAllowed] => [arrivalTime] => 07:00 AM <br>
[cancellationPolicy] => [<br>
{"cutoffTime":"1","refundInPercentage":"10"},<br>
{"cutoffTime":"2","refundInPercentage":"50"},<br>
{"cutoffTime":"4","refundInPercentage":"90"}<br>
] <br>
[boardingPoints] => Array ( [0] => Array ( [time] => 09:10PM [location] => Ameerpet,|Jeans Corner [id] => 6 ) [1] => Array ( [time] => 09:00PM [location] => S.R Nagar,S.R Nagar [id] => 2224 ) [2] => Array ( [time] => 08:30PM [location] => KUKATPALLY,JNTU [id] => 2230 ) ) [operatorName] => Dhanunjayabus [departureTime] => 9:00 PM [mTicketAllowed] => [idProofRequired] => [serviceId] => 6743 [fare] => 900 [busType] => VOLVO [routeScheduleId] => 6743 [commPCT] => 0 [operatorId] => 233 [inventoryType] => 0 )
)
)
Use a foreach() for it like so:
foreach ($your_response['apiAvailableBuses'] as $el) {
$cancellationPolicy[] = $el['cancellationPolicy'];
}
Try this:
foreach($data['apiStatus']['apiAvailableBuses'] as $item) {
foreach($item['cancellationPolicy'] as $key => $json) {
$jsonDecoded = json_decode($json, true);
// And you will have access to the data like this
// $jsonDecoded['cutoffTime'];
// $jsonDecoded['refundInPercentage'];
}
}
$response = json_decode($apiResponse);
$cancellationPolicies = [];
foreach ($response->apiAvailableBuses as $availableBus) {
$cancellationPolicies[] = $availableBus['cancellationPolicy'];
// if you want to display something you can simply do it like this;
echo $availableBus['cancellationPolicy']->cutoffTime;
}
How would i get the value of a key in an array?
The array is done by google shopping api which is:
// Valid source values are "public", "cx:cse", and "gan:pid"
// See http://code.google.com/apis/shopping/search/v1/getting_started.html#products-feed
$source = "public";
// For more information about full text search with the shopping API, please
// see http://code.google.com/apis/shopping/search/v1/getting_started.html#text-search
$query = "\"mp3 player\" | ipod";
//The order in which the API returns products is defined by a ranking criterion.
// See http://code.google.com/apis/shopping/search/v1/getting_started.html#ranking
$ranking = "relevancy";
$results = $service->products->listProducts($source, array(
"country" => "UK",
"q" => $query,
"rankBy" => $ranking,
));
print "<h1>Shopping Results</h1><pre>" . print_r($results, true) . "</pre>";
I have the following array which outputs:
Shopping Results
Array
(
[kind] => shopping#products
[etag] => "*********"
[id] => tag:google.com,2010:shopping/products
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products?country=UK&q=iphone&rankBy=relevancy
[nextLink] => https://www.googleapis.com/shopping/search/v1/public/products?country=UK&q=iphone&rankBy=relevancy&startIndex=26
[totalItems] => 771622
[startIndex] => 1
[itemsPerPage] => 25
[currentItemCount] => 25
[requestId] => 0CMjH976CqbECFYNWtAodLRwAAA
[items] => Array
(
[0] => Array
(
[kind] => shopping#product
[id] => tag:google.com,2010:shopping/products/5735617/11254757413841304510
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products/5735617/gid/11254757413841304510
[product] => Array
(
[googleId] => 11254757413841304510
[author] => Array
(
[name] => Amazon.co.uk
[accountId] => 5735617
)
[creationTime] => 2012-05-04T05:03:50.000Z
[modificationTime] => 2012-07-20T02:02:16.000Z
[country] => GB
[language] => en
[title] => Apple iPod touch 8GB - Black - 4th Generation (Latest Model - Launched Sept 2010)
[description] => Apple iPod touch 8GB - Black - 4th Generation (Latest Model - Launched Sept 2010)
[link] => http://www.amazon.co.uk/dp/B0040GIZTI/ref=asc_df_B0040GIZTI8843997?smid=A1YZ4RXO7GUOYN&tag=googlecouk06-21&linkCode=asn&creative=22218&creativeASIN=B0040GIZTI
[brand] => Apple
[condition] => new
[gtin] => 00885909394739
[gtins] => Array
(
[0] => 00885909394739
)
[mpns] => Array
(
[0] => MC540BT/A
)
[inventories] => Array
(
[0] => Array
(
[channel] => online
[availability] => inStock
[price] => 135.95
[shipping] => 1.99
[currency] => GBP
)
)
[images] => Array
(
[0] => Array
(
[link] => http://ecx.images-amazon.com/images/I/41p2rNmazRL.jpg
[status] => available
)
)
)
)
[1] => Array
(
[kind] => shopping#product
[id] => tag:google.com,2010:shopping/products/5735617/4597224105326146239
[selfLink] => https://www.googleapis.com/shopping/search/v1/public/products/5735617/gid/4597224105326146239
[product] => Array
(
[googleId] => 4597224105326146239
[author] => Array
(
[name] => Amazon.co.uk
[accountId] => 5735617
)
[creationTime] => 2012-05-04T05:03:50.000Z
[modificationTime] => 2012-07-20T02:02:16.000Z
[country] => GB
[language] => en
[title] => SanDisk Sansa Clip+ 8GB MP3 Player with Radio and Expandable MicroSD/SDHC Slot - Black
[description] => 8 GB memory Digital FM-tuner with 40 preset radio stations Extendable microSD/microSDHC card slot
[link] => http://www.amazon.co.uk/dp/B002NX0ME6/ref=asc_df_B002NX0ME68843997?smid=A3P5ROKL5A1OLE&tag=googlecouk06-21&linkCode=asn&creative=22206&creativeASIN=B002NX0ME6
[brand] => SanDisk
[condition] => new
[gtin] => 00619659059989
[gtins] => Array
(
[0] => 00619659059989
)
[mpns] => Array
(
[0] => SDMX18-008G-E46K
)
[inventories] => Array
(
[0] => Array
(
[channel] => online
[availability] => inStock
[price] => 46.95
[shipping] => 0
[currency] => GBP
)
)
[images] => Array
(
[0] => Array
(
[link] => http://ecx.images-amazon.com/images/I/419U6bYDF1L.jpg
[status] => available
)
)
)
)
I don't need all this data i just need 3-4 of the keys but how would i access them? How would i echo the value of say [title] from each array?
This should work:
foreach( $results as $result)
foreach( $result['product'] as $product)
echo $product['title'];
You could either loop through the array like pointed out above or possibly use array_walk_recursive like this:
$title_array = array();
array_walk_recursive($input_array, 'find_titles');
function find_titles($value, $key) {
global $title_array;
if ($key == 'title') {
$title_array[] = $value;
}
}
This might be a better solution if you you are not certain what the structure of the input array will be (i.e. how many levels deep the key you are looking for is nested).
To output the title of each product in $results:
foreach ($results as $result) {
echo $result['product']['title'];
}
Consider using array_walk_recursive
Working example
<?php
$a = array("hai", array("ha"=>1, "hai"=>2, array("a"=>1, "b"=>2)));
function test($item, $key)
{
echo "$key holds $item\n";
}
array_walk_recursive($a, 'test');
0 holds hai
ha holds 1
hai holds 2
a holds 1
b holds 2
If you are interested only in title
Consider using foreach
foreach($results['item'] as $result) {
echo $result['product']['title'];
}