Arrange values in array php / mysql - php

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!

Related

Retrieve a value from JSON Object using PHP (Shiprocket API)

I am getting below json data thru Shiprocket API. Now I want to extract value of below variables in PHP code from this json.
I have tried to use json_decode but it did not work and show null value:
$data = json_decode($json);
$sr_status = $data['shipment_status'];
Please suggest the code to retrieve below variables value.
shipment_status , awb_code , courier_company_id
Array
(
[0] => stdClass Object
(
[tracking_data] => stdClass Object
(
[track_status] => 1
[shipment_status] => 7
[shipment_track] => Array
(
[0] => stdClass Object
(
[id] => 180339484
[awb_code] => 11150911492
[courier_company_id] => 55
[shipment_id] => 1711169662
[order_id] => 233223781187
[pickup_date] => 2023-01-11 03:02:00
[delivered_date] => 2023-01-16 12:22:00
[weight] => 0.25
[packages] => 1
[current_status] => Delivered
[delivered_to] => Solapur
[destination] => Solapur
[consignee_name] => ABC
[origin] => Ludhiana
[courier_agent_details] =>
[edd] =>
)
)
[shipment_track_activities] => Array
(
[0] => stdClass Object
(
[date] => 2023-01-16 12:22:00
[status] => 000-T-DL
[activity] => SHIPMENT DELIVERED
[location] => SOLAPUR
[sr-status] => 7
[sr-status-label] => DELIVERED
)
[1] => stdClass Object
(
[date] => 2023-01-16 11:34:00
[status] => 002-S-UD
[activity] => SHIPMENT OUTSCAN
[location] => SOLAPUR
[sr-status] => 17
[sr-status-label] => OUT FOR DELIVERY
)
)
[track_url] => https://shiprocket.co//tracking/11150911492
[etd] => 2023-01-14 17:02:00
[qc_response] => stdClass Object
(
[qc_image] =>
[qc_failed_reason] =>
)
)
)
)
you can try this:
$array = ...; // Your array here
$data= json_decode($array);
$shipment_status = $data[0]->tracking_data->shipment_status;
$awb_code = $data[0]->tracking_data->shipment_track[0]->awb_code;
$courier_company_id = $data[0]->tracking_data->shipment_track[0]->courier_company_id;
Or use $data = json_decode($json,true); which return an array where you can use
foreach($data as $val) {
$shipment_status = $val['tracking_data']['shipment_status'];
foreach ($val['shipment_track'] as $value) {
$awb_code = $value['awb_code'];
$courier_company_id = $value['courier_company_id'];
}
}

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'].

How to write Laravel Query in two parts

I am working with Laravel 5.2. I want to write a query in two parts like this:
$getData = DB::table($table)
->where($where);
$getData->first();
return $getData;
But it is not working for me. It Not provides correct data to me.
It gives:
Array ( [aggregate] => [columns] => [distinct] => [from] => countries [joins] => [wheres] => Array ( [0] => Array ( [type] => Nested [query] => Array ( [aggregate] => [columns] => [distinct] => [from] => countries [joins] => [wheres] => Array ( [0] => Array ( [type] => Basic [column] => country_name [operator] => = [value] => India [boolean] => and ) ) [groups] => [havings] => [orders] => [limit] => [offset] => [unions] => [unionLimit] => [unionOffset] => [unionOrders] => [lock] => ) [boolean] => and ) ) [groups] => [havings] => [orders] => [limit] => 1 [offset] => [unions] => [unionLimit] => [unionOffset] => [unionOrders] => [lock] => )
But it works correctly when i call like this:
$getData = DB::table($table)
->where($where)->first();
return $getData;
Can we not call a query in two parts in laravel.
You have to get back the returned data from $getData->first();
$getData = DB::table($table)
->where($where);
$getData = $getData->first(); // <----
return $getData;

Extract data from Array/Object in PHP?

First off, I'm new to PHP and coding in general, so this might be quite an obvious answer.
I'm currently working with the Strava API, and I'm trying to extract data from an Array/Object which is the result of the following API call:
$recentactivities = $api->get('athlete/activities', array('per_page' => 100));
which returns:
Array (
[1] => stdClass Object (
[id] => XXXX
[resource_state] => 2
[external_id] => XXXX
[upload_id] => XXXX
[athlete] => stdClass Object (
[id] => XXXX
[resource_state] => 1
)
[name] => Let\'s see if I can remember how to do this cycling malarkey...
[distance] => 11858.3
[moving_time] => 1812
[elapsed_time] => 2220
[total_elevation_gain] => 44
[type] => Ride
[start_date] => 2014-07-12T13:48:17Z
[start_date_local] => 2014-07-12T14:48:17Z
[timezone] => (
GMT+00:00
) Europe/London
[start_latlng] => Array (
[0] => XXXX
[1] => XXXX
)
[end_latlng] => Array (
[0] => XXXX
[1] => -XXXX
)
[location_city] => XXXX
[location_state] => England
[location_country] => United Kingdom
[start_latitude] => XXXX
[start_longitude] => XXXXX
[achievement_count] => 4
[kudos_count] => 1
[comment_count] => 0
[athlete_count] => 1
[photo_count] => 0
[map] => stdClass Object (
[id] => a164894160
[summary_polyline] => XXXX
[resource_state] => 2
)
[trainer] =>
[commute] =>
[manual] =>
[private] =>
[flagged] =>
[gear_id] => b739244
[average_speed] => 6.544
[max_speed] => 10.8
[average_cadence] => 55.2
[average_temp] => 29
[average_watts] => 99.3
[kilojoules] => 179.9
[device_watts] =>
[average_heartrate] => 191.2
[max_heartrate] => 200
[truncated] =>
[has_kudoed] =>
)
This repeats for the most recent activities.
I'm attempting to extract average_heartrate, which I can do for a single object using the following:
$recentactivities[1]->average_heartrate;
but I'd like to extract all instances of average_heartrate from the Array. I've tried to use a foreach statement, but to be honest, I have no idea where to start.
Any help would be much appreciated.
It's actually pretty simple you can indeed use a foreach loop:
foreach($myArray as $obj){
//$obj is an object so:
if(isset($obj->average_heartrate)){
echo $obj->average_heartrate;
}
}
With this code you iterate through your array with objects and save the wanted array within an array so you can work further with it.
$heartrateArray = array(); // create a new array
//iterate through it with an foreach
foreach($recentactivities as $activity){
// save the average_heartrate as a value under a new key in the array
$heartrateArray[] = $activity->average_heartrate;
}

parse PHP array

I have managed to get to the stage where I have an array that looks like this. Used (zend_json to decode a json response)
Array
(
[response] => Array
(
[status] => ok
[userTier] => free
[total] => 10
[startIndex] => 1
[pageSize] => 10
[currentPage] => 1
[pages] => 1
[results] => Array
(
[0] => Array
(
[id] => lifeandstyle/series/cycling
[type] => series
[webTitle] => Cycling
[webUrl] => http://www.guardian.co.uk/lifeandstyle/series/cycling
[apiUrl] => http://content.guardianapis.com/lifeandstyle/series/cycling
[sectionId] => lifeandstyle
[sectionName] => Life and style
)
[1] => Array
(
[id] => sport/cycling
[type] => keyword
[webTitle] => Cycling
[webUrl] => http://www.guardian.co.uk/sport/cycling
[apiUrl] => http://content.guardianapis.com/sport/cycling
[sectionId] => sport
[sectionName] => Sport
)
How would I go about parsing only the elements that are [webTitle] and [webUrl]
Thanks!
You can't specifically parse only those parts, but you can iterate over the results and access them.
foreach ($val['response']['results'] as $result) {
$title = $result['webTitle'];
$url = $result['webUrl'];
// ...
}

Categories