PHP- How do I reduce array based on a key's value - php

I have an array like this:
Array
(
[0] => Array
(
[CommodityID] => 10
[RetailerID] => 1798
[Name] => Petrol
[City] => Parow
[Line1] => 49 Fifth Avenue
[Line2] =>
[Line3] =>
[ContractorName] => BP Fifth Ave Motors Parow
[AreaCode] => 021
[Number] => 9305025
[Latitude] => -33.896493
[Longitude] => 18.579302
[LogoUrl] => https://webservices.test.com/ContractorLogos/bp.png
[dist] => 0.00
)
[1] => Array
(
[CommodityID] => 10
[RetailerID] => 1798
[Name] => Petrol
[City] => Parow
[Line1] => 49 Fifth Avenue
[Line2] =>
[Line3] =>
[ContractorName] => BP Fifth Ave Motors Parow
[AreaCode] => 021
[Number] => 9305025
[Latitude] => -33.896493
[Longitude] => 18.579302
[LogoUrl] => https://webservices.test.com/ContractorLogos/bp.png
[dist] => 0.00
)
[2] => Array
(
[CommodityID] => 22
[RetailerID] => 1758
[Name] => Jewellers
[City] => Parow
[Line1] => Shop 4
[Line2] => Mc Intyre Square
[Line3] => Mc Intyre Road
[ContractorName] => Du Plessis Manufacturing Jewellers Parow
[AreaCode] => 021
[Number] => 9300788
[Latitude] => -33.895200
[Longitude] => 18.586710
[LogoUrl] => https://webservices.test.com/ContractorLogos/DuPlessisJewellers.png
[dist] => 0.01
)
)
I simply want to have only unique [RetailerID] i.e:
Array
(
[0] => Array
(
[CommodityID] => 10
[RetailerID] => 1798
[Name] => Petrol
[City] => Parow
[Line1] => 49 Fifth Avenue
[Line2] =>
[Line3] =>
[ContractorName] => BP Fifth Ave Motors Parow
[AreaCode] => 021
[Number] => 9305025
[Latitude] => -33.896493
[Longitude] => 18.579302
[LogoUrl] => https://webservices.test.com/ContractorLogos/bp.png
[dist] => 0.00
)
[1] => Array
(
[CommodityID] => 22
[RetailerID] => 1758
[Name] => Jewellers
[City] => Parow
[Line1] => Shop 4
[Line2] => Mc Intyre Square
[Line3] => Mc Intyre Road
[ContractorName] => Du Plessis Manufacturing Jewellers Parow
[AreaCode] => 021
[Number] => 9300788
[Latitude] => -33.895200
[Longitude] => 18.586710
[LogoUrl] => https://webservices.test.com/ContractorLogos/DuPlessisJewellers.png
[dist] => 0.01
)
)
I have tried array_unique, but that seems to make it unique based on all columns. Is there a php built-in function that can do this by looking at just one array key's value?

would iterate the array once and save only unique values by that field once, for example:
$newArray = array();
foreach($array as $item) {
$newArray[$item['RetailerID']] = $item;
}
this will always save only the last item of the same kind. you can modify the logic to match your needs.
another, more safe possibility would be saving the unique values and checking them:
$exists = array();
$newArray = array();
foreach($array as $item) {
if(!in_array($item['RetailerID'],$exists)){
$newArray[$item['RetailerID']] = $item;
$exists[] = $item['RetailerID'];
}
}

Related

Using array_chunk on multi array

I have a multi dimensional array and i am now sure how to use array chunk on my array key request while preserving the information into the new array. I would like to split the array every 2 arrays. I tried using array_chunk inside of a loop but no luck.
Here is my array.
[0] => Array
(
[first_name] => Richard
[patient_first_name] => Donna
[trip_date] => 2018-08-24
[request] => Array
(
[0] => stdClass Object
(
[id] => 46
[client_id] => 9873
[city] => COOLIDGE
[state] => AZ
[zip] => 85228
)
[1] => stdClass Object
(
[id] => 49
[client_id] => 14965
[city] => CHANDLER
[state] => AZ
[zip] => 85226
)
[2] => stdClass Object
(
[id] => 55
[client_id] => 10120
[city] => PHX
[state] => AZ
[zip] => 85008
)
[3] => stdClass Object
(
[id] => 59
[client_id] => 11229
[city] => BUCKEYE
[state] => AZ
[zip] => 85326
)
[4] => stdClass Object
(
[id] => 69
[client_id] => 13769
[city] => PHOENIX
[state] => AZ
[zip] => 85035
)
[5] => stdClass Object
(
[id] => 175
[client_id] => 16437
[city] => Phx
[state] => Az
[zip] => 85029
)
[6] => stdClass Object
(
[id] => 195
[client_id] => 16457
[city] => Apache Junction
[state] => Az
[zip] => 85120
)
[7] => stdClass Object
(
[id] => 197
[client_id] => 16459
[city] => Mesa
[state] => Az
[zip] => 85204
)
)
)
This is the array I would like.
[0] => Array
(
[first_name] => Richard
[patient_first_name] => Donna
[trip_date] => 2018-08-24
[request] => Array
(
[0] => stdClass Object
(
[id] => 46
[client_id] => 9873
[city] => COOLIDGE
[state] => AZ
[zip] => 85228
)
[1] => stdClass Object
(
[id] => 49
[client_id] => 14965
[city] => CHANDLER
[state] => AZ
[zip] => 85226
)
)
[1] => Array
(
[first_name] => Richard
[patient_first_name] => Donna
[trip_date] => 2018-08-24
[request] => Array
[0] => stdClass Object
(
[id] => 55
[client_id] => 10120
[city] => PHX
[state] => AZ
[zip] => 85008
)
[1] => stdClass Object
(
[id] => 59
[client_id] => 11229
[city] => BUCKEYE
[state] => AZ
[zip] => 85326
)
)
[2] => Array
(
[first_name] => Richard
[patient_first_name] => Donna
[trip_date] => 2018-08-24
[request] => Array
[0] => stdClass Object
(
[id] => 69
[client_id] => 13769
[city] => PHOENIX
[state] => AZ
[zip] => 85035
)
[1] => stdClass Object
(
[id] => 175
[client_id] => 16437
[city] => Phx
[state] => Az
[zip] => 85029
)
)
)
This is my code.
$drivers = [];
foreach($recs as $val => $rec) {
$drivers[$rec->driver_id]['first_name'] = $rec->first_name;
$drivers[$rec->driver_id]['patient_first_name'] = $rec->patient_first_name;
$drivers[$rec->driver_id]['trip_date'] = $rec->trip_date;
$drivers[$rec->driver_id]['request'][] = $rec;
}
foreach($drivers as $val => $driver) {
$drivers = array_chunk($driver['request'], 2);
}
Any suggestions?
Using array-chunk if what you need. Check the following example (I remove some of the data to simplify):
$request = array(["id" => 46], ["id" => 49], ["id" => 55], ["id" => 59], ["id" => 69], ["id" => 175], ["id" => 195], ["id" => 197]);
$arr[] = array("first_name" => "Richard", "request" => $request);
foreach($arr as $driver) {
$requests = array_chunk($driver['request'], 2);
foreach($requests as $chunck) {
$ans[] = array("id" => $driver["first_name"], "request" => $chunck); // here you can add all the other data you need from the "driver" object
}
}
Now , $ans will have your desire output
Get 'request' from the source array, chunk it and add rest items to each element of the result array
$res = array_chunk($recs['request'], 2);
unset($recs['request']);
foreach($res as &$x) {
$x += $recs;
}

PHP - Looping through indexed JSON array

I have parsed and looped through JSON plenty of times. I have seemed to hit a wall with something I have not done before and I have been unable to find an answer and hopefully I am referencing this correctly. I have been really struggling with this.
With the code example below I can parse it and assign a varible to an object and get its value like so.
$result = json_decode($json, true);
print_r($result);
echo $result['response'][0]['report']['type'];
This is where the problem comes in and it starts with the array index and I am hoping I am referring to this correctly. Basically it is the [0] from above. I have never looped through something like that before and my research has come up empty. Normally I would do it like this.
$json = '{"success":true,"error":null,"response":[{"id":"59c30487db6be86b7f8b465a","loc":{"long":-90.45,"lat":43.43},"report":{"code":"R","type":"heavy rain","name":"Gillingham","detail":{"text":1,"rainIN":1,"rainMM":25.4},"reporter":"co-op observer","comments":"","timestamp":1505952240,"cat":"rain","dateTimeISO":"2017-09-20T19:04:00-05:00","datetime":"2017-09-20T19:04:00-05:00","wfo":"arx"},"place":{"name":"gillingham","state":"wi","county":"richland","country":"us"},"profile":{"tz":"America\/Chicago"}},{"id":"59c302a9db6be82a758b46e8","loc":{"long":-90.93,"lat":43.32},"report":{"code":"R","type":"heavy rain","name":"Mount Sterling","detail":{"text":2.25,"rainIN":2.25,"rainMM":57.15},"reporter":"trained spotter","comments":"","timestamp":1505951760,"cat":"rain","dateTimeISO":"2017-09-20T18:56:00-05:00","datetime":"2017-09-20T18:56:00-05:00","wfo":"arx"},"place":{"name":"mount sterling","state":"wi","county":"crawford","country":"us"},"profile":{"tz":"America\/Chicago"}},{"id":"59c30106db6be8146c8b4661","loc":{"long":-89.53,"lat":44.45},"report":{"code":"R","type":"heavy rain","name":"Plover","detail":{"text":1.05,"rainIN":1.05,"rainMM":26.67},"reporter":"co-op observer","comments":"One hour total rainfall. also measured a 49 mph wind gust at 511 pm. no hail.","timestamp":1505950800,"cat":"rain","dateTimeISO":"2017-09-20T18:40:00-05:00","datetime":"2017-09-20T18:40:00-05:00","wfo":"grb"},"place":{"name":"plover","state":"wi","county":"portage","country":"us"},"profile":{"tz":"America\/Chicago"}},{"id":"59c3080adb6be8d5138b4654","loc":{"long":-89.33,"lat":44.37},"report":{"code":"H","type":"hail","name":"4 mi NNW Blaine","detail":{"text":0.88,"hailIN":0.88,"hailMM":22.35},"reporter":"trained spotter","comments":"Nickel size hail and heavy rain. 3.25 to 3.49 inches in the past 2 hours.","timestamp":1505950680,"cat":"hail","dateTimeISO":"2017-09-20T18:38:00-05:00","datetime":"2017-09-20T18:38:00-05:00","wfo":"grb"},"place":{"name":"blaine","state":"wi","county":"portage","country":"us"},"profile":{"tz":"America\/Chicago"}},{"id":"59c30106db6be8146c8b4660","loc":{"long":-90.93,"lat":43.32},"report":{"code":"H","type":"hail","name":"Mount Sterling","detail":{"text":0.75,"hailIN":0.75,"hailMM":19.05},"reporter":"trained spotter","comments":"Hail ranged from 1\/2 to 3\/4 inch.","timestamp":1505950200,"cat":"hail","dateTimeISO":"2017-09-20T18:30:00-05:00","datetime":"2017-09-20T18:30:00-05:00","wfo":"arx"},"place":{"name":"mount sterling","state":"wi","county":"crawford","country":"us"},"profile":{"tz":"America\/Chicago"}},{"id":"59c2fd80db6be844598b466d","loc":{"long":-89.77,"lat":44.21},"report":{"code":"R","type":"heavy rain","name":"6 mi ESE New Rome","detail":{"text":4,"rainIN":4,"rainMM":101.6},"reporter":"trained spotter","comments":"","timestamp":1505949840,"cat":"rain","dateTimeISO":"2017-09-20T18:24:00-05:00","datetime":"2017-09-20T18:24:00-05:00","wfo":"arx"},"place":{"name":"rome","state":"wi","county":"adams","country":"us"},"profile":{"tz":"America\/Chicago"}},{"id":"59c2f678db6be898338b4673","loc":{"long":-89.3,"lat":44.46},"report":{"code":"H","type":"hail","name":"Amherst Junction","detail":{"text":1,"hailIN":1,"hailMM":25.4},"reporter":"trained spotter","comments":"","timestamp":1505948340,"cat":"hail","dateTimeISO":"2017-09-20T17:59:00-05:00","datetime":"2017-09-20T17:59:00-05:00","wfo":"grb"},"place":{"name":"amherst junction","state":"wi","county":"portage","country":"us"},"profile":{"tz":"America\/Chicago"}},{"id":"59c2f2f6db6be8a2208b4672","loc":{"long":-89.4,"lat":44.26},"report":{"code":"H","type":"hail","name":"Almond","detail":{"text":2,"hailIN":2,"hailMM":50.8},"reporter":"trained spotter","comments":"Report via social media","timestamp":1505948160,"cat":"hail","dateTimeISO":"2017-09-20T17:56:00-05:00","datetime":"2017-09-20T17:56:00-05:00","wfo":"grb"},"place":{"name":"almond","state":"wi","county":"portage","country":"us"},"profile":{"tz":"America\/Chicago"}}]}';
$result = json_decode($json, true);
print_r($result);
foreach($result as report) {
$type = $report['report']['type'];
echo $type;
}
That would usually work in most cases but since this has the [0] and increases with each new entry I am not sure how to loop through that as my entry point is different that what I have dealt with before and have been unable to find any working examples for something like this. Not to mention I am not sure how to working ['response'] into the loop ether with those index keys.
Here is a decode example of the array and what I am working with.
Array ( [success] => 1 [error] => [response] => Array ( [0] => Array ( [id] => 59c30487db6be86b7f8b465a [loc] => Array ( [long] => -90.45 [lat] => 43.43 ) [report] => Array ( [code] => R [type] => heavy rain [name] => Gillingham [detail] => Array ( [text] => 1 [rainIN] => 1 [rainMM] => 25.4 ) [reporter] => co-op observer [comments] => [timestamp] => 1505952240 [cat] => rain [dateTimeISO] => 2017-09-20T19:04:00-05:00 [datetime] => 2017-09-20T19:04:00-05:00 [wfo] => arx ) [place] => Array ( [name] => gillingham [state] => wi [county] => richland [country] => us ) [profile] => Array ( [tz] => America/Chicago ) ) [1] => Array ( [id] => 59c302a9db6be82a758b46e8 [loc] => Array ( [long] => -90.93 [lat] => 43.32 ) [report] => Array ( [code] => R [type] => heavy rain [name] => Mount Sterling [detail] => Array ( [text] => 2.25 [rainIN] => 2.25 [rainMM] => 57.15 ) [reporter] => trained spotter [comments] => [timestamp] => 1505951760 [cat] => rain [dateTimeISO] => 2017-09-20T18:56:00-05:00 [datetime] => 2017-09-20T18:56:00-05:00 [wfo] => arx ) [place] => Array ( [name] => mount sterling [state] => wi [county] => crawford [country] => us ) [profile] => Array ( [tz] => America/Chicago ) ) [2] => Array ( [id] => 59c30106db6be8146c8b4661 [loc] => Array ( [long] => -89.53 [lat] => 44.45 ) [report] => Array ( [code] => R [type] => heavy rain [name] => Plover [detail] => Array ( [text] => 1.05 [rainIN] => 1.05 [rainMM] => 26.67 ) [reporter] => co-op observer [comments] => One hour total rainfall. also measured a 49 mph wind gust at 511 pm. no hail. [timestamp] => 1505950800 [cat] => rain [dateTimeISO] => 2017-09-20T18:40:00-05:00 [datetime] => 2017-09-20T18:40:00-05:00 [wfo] => grb ) [place] => Array ( [name] => plover [state] => wi [county] => portage [country] => us ) [profile] => Array ( [tz] => America/Chicago ) ) [3] => Array ( [id] => 59c3080adb6be8d5138b4654 [loc] => Array ( [long] => -89.33 [lat] => 44.37 ) [report] => Array ( [code] => H [type] => hail [name] => 4 mi NNW Blaine [detail] => Array ( [text] => 0.88 [hailIN] => 0.88 [hailMM] => 22.35 ) [reporter] => trained spotter [comments] => Nickel size hail and heavy rain. 3.25 to 3.49 inches in the past 2 hours. [timestamp] => 1505950680 [cat] => hail [dateTimeISO] => 2017-09-20T18:38:00-05:00 [datetime] => 2017-09-20T18:38:00-05:00 [wfo] => grb ) [place] => Array ( [name] => blaine [state] => wi [county] => portage [country] => us ) [profile] => Array ( [tz] => America/Chicago ) ) [4] => Array ( [id] => 59c30106db6be8146c8b4660 [loc] => Array ( [long] => -90.93 [lat] => 43.32 ) [report] => Array ( [code] => H [type] => hail [name] => Mount Sterling [detail] => Array ( [text] => 0.75 [hailIN] => 0.75 [hailMM] => 19.05 ) [reporter] => trained spotter [comments] => Hail ranged from 1/2 to 3/4 inch. [timestamp] => 1505950200 [cat] => hail [dateTimeISO] => 2017-09-20T18:30:00-05:00 [datetime] => 2017-09-20T18:30:00-05:00 [wfo] => arx ) [place] => Array ( [name] => mount sterling [state] => wi [county] => crawford [country] => us ) [profile] => Array ( [tz] => America/Chicago ) ) [5] => Array ( [id] => 59c2fd80db6be844598b466d [loc] => Array ( [long] => -89.77 [lat] => 44.21 ) [report] => Array ( [code] => R [type] => heavy rain [name] => 6 mi ESE New Rome [detail] => Array ( [text] => 4 [rainIN] => 4 [rainMM] => 101.6 ) [reporter] => trained spotter [comments] => [timestamp] => 1505949840 [cat] => rain [dateTimeISO] => 2017-09-20T18:24:00-05:00 [datetime] => 2017-09-20T18:24:00-05:00 [wfo] => arx ) [place] => Array ( [name] => rome [state] => wi [county] => adams [country] => us ) [profile] => Array ( [tz] => America/Chicago ) ) [6] => Array ( [id] => 59c2f678db6be898338b4673 [loc] => Array ( [long] => -89.3 [lat] => 44.46 ) [report] => Array ( [code] => H [type] => hail [name] => Amherst Junction [detail] => Array ( [text] => 1 [hailIN] => 1 [hailMM] => 25.4 ) [reporter] => trained spotter [comments] => [timestamp] => 1505948340 [cat] => hail [dateTimeISO] => 2017-09-20T17:59:00-05:00 [datetime] => 2017-09-20T17:59:00-05:00 [wfo] => grb ) [place] => Array ( [name] => amherst junction [state] => wi [county] => portage [country] => us ) [profile] => Array ( [tz] => America/Chicago ) ) [7] => Array ( [id] => 59c2f2f6db6be8a2208b4672 [loc] => Array ( [long] => -89.4 [lat] => 44.26 ) [report] => Array ( [code] => H [type] => hail [name] => Almond [detail] => Array ( [text] => 2 [hailIN] => 2 [hailMM] => 50.8 ) [reporter] => trained spotter [comments] => Report via social media [timestamp] => 1505948160 [cat] => hail [dateTimeISO] => 2017-09-20T17:56:00-05:00 [datetime] => 2017-09-20T17:56:00-05:00 [wfo] => grb ) [place] => Array ( [name] => almond [state] => wi [county] => portage [country] => us ) [profile] => Array ( [tz] => America/Chicago ) ) ) )
How would I loop through this with the Index key [#] and if I am referring to this incorrectly feel free to correct me.
You can use loop in $result["response"] as:
$json = '{"success":true,"error":null,"response":[{"id":"59c30487db6be86b7f8b465a","loc":{"long":-90.45,"lat":43.43},"report":{"code":"R","type":"heavy rain","name":"Gillingham","detail":{"text":1,"rainIN":1,"rainMM":25.4},"reporter":"co-op observer","comments":"","timestamp":1505952240,"cat":"rain","dateTimeISO":"2017-09-20T19:04:00-05:00","datetime":"2017-09-20T19:04:00-05:00","wfo":"arx"},"place":{"name":"gillingham","state":"wi","county":"richland","country":"us"},"profile":{"tz":"America\/Chicago"}},{"id":"59c302a9db6be82a758b46e8","loc":{"long":-90.93,"lat":43.32},"report":{"code":"R","type":"heavy rain","name":"Mount Sterling","detail":{"text":2.25,"rainIN":2.25,"rainMM":57.15},"reporter":"trained spotter","comments":"","timestamp":1505951760,"cat":"rain","dateTimeISO":"2017-09-20T18:56:00-05:00","datetime":"2017-09-20T18:56:00-05:00","wfo":"arx"},"place":{"name":"mount sterling","state":"wi","county":"crawford","country":"us"},"profile":{"tz":"America\/Chicago"}},{"id":"59c30106db6be8146c8b4661","loc":{"long":-89.53,"lat":44.45},"report":{"code":"R","type":"heavy rain","name":"Plover","detail":{"text":1.05,"rainIN":1.05,"rainMM":26.67},"reporter":"co-op observer","comments":"One hour total rainfall. also measured a 49 mph wind gust at 511 pm. no hail.","timestamp":1505950800,"cat":"rain","dateTimeISO":"2017-09-20T18:40:00-05:00","datetime":"2017-09-20T18:40:00-05:00","wfo":"grb"},"place":{"name":"plover","state":"wi","county":"portage","country":"us"},"profile":{"tz":"America\/Chicago"}},{"id":"59c3080adb6be8d5138b4654","loc":{"long":-89.33,"lat":44.37},"report":{"code":"H","type":"hail","name":"4 mi NNW Blaine","detail":{"text":0.88,"hailIN":0.88,"hailMM":22.35},"reporter":"trained spotter","comments":"Nickel size hail and heavy rain. 3.25 to 3.49 inches in the past 2 hours.","timestamp":1505950680,"cat":"hail","dateTimeISO":"2017-09-20T18:38:00-05:00","datetime":"2017-09-20T18:38:00-05:00","wfo":"grb"},"place":{"name":"blaine","state":"wi","county":"portage","country":"us"},"profile":{"tz":"America\/Chicago"}},{"id":"59c30106db6be8146c8b4660","loc":{"long":-90.93,"lat":43.32},"report":{"code":"H","type":"hail","name":"Mount Sterling","detail":{"text":0.75,"hailIN":0.75,"hailMM":19.05},"reporter":"trained spotter","comments":"Hail ranged from 1\/2 to 3\/4 inch.","timestamp":1505950200,"cat":"hail","dateTimeISO":"2017-09-20T18:30:00-05:00","datetime":"2017-09-20T18:30:00-05:00","wfo":"arx"},"place":{"name":"mount sterling","state":"wi","county":"crawford","country":"us"},"profile":{"tz":"America\/Chicago"}},{"id":"59c2fd80db6be844598b466d","loc":{"long":-89.77,"lat":44.21},"report":{"code":"R","type":"heavy rain","name":"6 mi ESE New Rome","detail":{"text":4,"rainIN":4,"rainMM":101.6},"reporter":"trained spotter","comments":"","timestamp":1505949840,"cat":"rain","dateTimeISO":"2017-09-20T18:24:00-05:00","datetime":"2017-09-20T18:24:00-05:00","wfo":"arx"},"place":{"name":"rome","state":"wi","county":"adams","country":"us"},"profile":{"tz":"America\/Chicago"}},{"id":"59c2f678db6be898338b4673","loc":{"long":-89.3,"lat":44.46},"report":{"code":"H","type":"hail","name":"Amherst Junction","detail":{"text":1,"hailIN":1,"hailMM":25.4},"reporter":"trained spotter","comments":"","timestamp":1505948340,"cat":"hail","dateTimeISO":"2017-09-20T17:59:00-05:00","datetime":"2017-09-20T17:59:00-05:00","wfo":"grb"},"place":{"name":"amherst junction","state":"wi","county":"portage","country":"us"},"profile":{"tz":"America\/Chicago"}},{"id":"59c2f2f6db6be8a2208b4672","loc":{"long":-89.4,"lat":44.26},"report":{"code":"H","type":"hail","name":"Almond","detail":{"text":2,"hailIN":2,"hailMM":50.8},"reporter":"trained spotter","comments":"Report via social media","timestamp":1505948160,"cat":"hail","dateTimeISO":"2017-09-20T17:56:00-05:00","datetime":"2017-09-20T17:56:00-05:00","wfo":"grb"},"place":{"name":"almond","state":"wi","county":"portage","country":"us"},"profile":{"tz":"America\/Chicago"}}]}';
$result = json_decode($json, true);
foreach($result["response"] as $report) {
$type = $report['report']['type'];
echo $type;
}
Check the result here: http://sandbox.onlinephpfunctions.com/code/c7b55a67e649bdc8c35ec1ba8218747de1f8ac16

Looping in a complex array

hope you are fine today.
I have an xml file online that I stored it into an array using file_get_contents(), simplexml_load_string() json_encode and json_decode; using the above methods gave an array like this:
[data] => Array
(
[transaction] => Array
(
[0] => Array
(
[fields] => Array
(
[transactionid] => 90397725
[transactionreference] => 90397725
[transactiontime] => 14:34:56
[transactiondate] => 2016-04-08
[upgauthcode] => 649192
[cardnumber] => ***************5104
[cardholdersname] => MISS Jane K Doe
[switchnumber] => Array
(
)
[cardstartyear] => 15
[cardstartmonth] => 02
[cardexpireyear] => 20
[cardexpiremonth] => 02
[transactionamount] => 108.00
[cardtype] => VISADEBIT
[baskettype] => order
[regisalu] => Miss
[regifnam] => Jane
[regilnam] => Doe
[regiadd1] => 14 Test Street
[regiadd4] => Test
[regiadd5] => West Test
[regiadd6] => fg28 5nZ
[regiadd7] => United Kingdom
[regidnum] => 07464000000
[regienum] => 07464000000
[regimobi] => 07464000000
[maddsalu] => Miss
[maddfnam] => Jane
[maddlnam] => Doe
[maddadd1] => 14 Test Street
[maddadd4] => Test
[maddadd5] => West Test
[maddadd6] => fg28 5nZ
[maddadd7] => United Kingdom
[madddnum] => 07464000000
[maddenum] => 07464000000
[maddidel] => Deliver
[baskettotal] => 90.00
[hirewaivertotal] => 0.00
[deliverytotal] => 0.00
[collectiontotal] => 0.00
[cardholderaddr1] => 14 Test Street
[cardholderaddr2] => Array
(
)
[cardholdercity] => Test
[cardholderstate] => West Test
[cardholderpostcode] => fg28 5nZ
[cardholdercountry] => United Kingdom
[regiuser] => jane.doe#gmail.com
[regihtml] => 0
[regigrde] => 0
[regigrdn] => 0
[regipopt] => 0
[maddcoll] => 1
[maddgrde] => 0
[maddgrdn] => 0
)
[orderitems] => Array
(
[item] => Array
(
[code] => DL008
[sku] => Array
(
)
[desc] => 22M LED Festoon (230v)
[description] => DL008, 22M LED Festoon (230v)
[price] => 45.00
[qty] => 2
[totalprice] => 90.00
)
)
)
[45] => Array
(
[fields] => Array
(
[transactionid] => 93645131
[transactionreference] => 93645131
[transactiontime] => 14:15:16
[transactiondate] => 2016-07-07
[upgauthcode] => 085526
[cardnumber] => ***************0103
[cardholdersname] => John Doe
[switchnumber] => Array
(
)
[cardstartyear] => 15
[cardstartmonth] => 12
[cardexpireyear] => 18
[cardexpiremonth] => 11
[transactionamount] => 588.00
[cardtype] => MASTERCARD
[baskettype] => order
[regisalu] => Mr
[regifnam] => John
[regilnam] => Doe
[regiadd1] => 39-45 TEST SQUARE
[regiadd2] => CITY Test Aquarium
[regiadd4] => London
[regiadd6] => bb2A 1op
[regiadd7] => United Kingdom
[regidnum] => 074640000000
[regienum] => 074640000000
[regimobi] => 07464000000
[maddsalu] => Mr
[maddfnam] => John
[maddlnam] => Doe
[maddadd1] => 39-45 TEST SQUARE
[maddadd2] => CITY Test AQUARIUM
[maddadd4] => London
[maddadd6] => bb2A 1op
[maddadd7] => United Kingdom
[madddnum] => 07464000000
[maddenum] => 07464000000
[maddidel] => Deliver
[baskettotal] => 490.00
[hirewaivertotal] => 0.00
[deliverytotal] => 0.00
[collectiontotal] => 0.00
[cardholderaddr1] => 39-45 TEST SQUARE
[cardholderaddr2] => CITY TEST AQUARIUM
[cardholdercity] => London
[cardholderpostcode] => bb2A 1op
[cardholdercountry] => United Kingdom
[regiuser] => john.doe#bloomberg.net
[regihtml] => 0
[regipopt] => 1
[regigrde] => 0
[regigrdn] => 0
[maddcoll] => 1
[maddgrde] => 0
[maddgrdn] => 0
)
[orderitems] => Array
(
[item] => Array
(
[0] => Array
(
[code] => PK289
[sku] => Array
(
)
[desc] => EvoLite Helmet STD Peak (white)
[description] => PK289, EvoLite Helmet STD Peak (white)
[price] => 9.00
[qty] => 6
[totalprice] => 54.00
)
[1] => Array
(
[code] => GGE3
[sku] => Array
(
)
[desc] => Graft Gear Safety Spectacle
[description] => GGE3, Graft Gear Safety Spectacle
[price] => 2.00
[qty] => 6
[totalprice] => 12.00
)
[2] => Array
(
[code] => GG025
[sku] => Array
(
)
[desc] => Graft Gear Hi-Vis Vest (M)
[description] => GG025, Graft Gear Hi-Vis Vest (M)
[price] => 5.00
[qty] => 2
[totalprice] => 10.00
)
[3] => Array
(
[code] => GG027
[sku] => Array
(
)
[desc] => Graft Gear Hi-Vis Vest (XL)
[description] => GG027, Graft Gear Hi-Vis Vest (XL)
[price] => 5.00
[qty] => 4
[totalprice] => 20.00
)
[4] => Array
(
[code] => GG029
[sku] => Array
(
)
[desc] => Graft Gear Hi-Vis Vest (3XL)
[description] => GG029, Graft Gear Hi-Vis Vest (3XL)
[price] => 5.00
[qty] => 4
[totalprice] => 20.00
)
[5] => Array
(
[code] => GG030
[sku] => Array
(
)
[desc] => Graft Gear Hi-Vis Vest (4XL)
[description] => GG030, Graft Gear Hi-Vis Vest (4XL)
[price] => 5.00
[qty] => 2
[totalprice] => 10.00
)
[6] => Array
(
[code] => GG037
[sku] => Array
(
)
[desc] => Graft Gear Bomber (M)
[description] => GG037, Graft Gear Bomber (M)
[price] => 23.00
[qty] => 1
[totalprice] => 23.00
)
[7] => Array
(
[code] => GG039
[sku] => Array
(
)
[desc] => Graft Gear Bomber (XL)
[description] => GG039, Graft Gear Bomber (XL)
[price] => 23.00
[qty] => 2
[totalprice] => 46.00
)
[8] => Array
(
[code] => GG041
[sku] => Array
(
)
[desc] => Graft Gear Bomber (XXXL)
[description] => GG041, Graft Gear Bomber (XXXL)
[price] => 23.00
[qty] => 3
[totalprice] => 69.00
)
[9] => Array
(
[code] => GG073
[sku] => Array
(
)
[desc] => Nubuck Mid-Cut Safety Boot
[description] => GG073, Nubuck Mid-Cut Safety Boot
[price] => 39.00
[qty] => 1
[totalprice] => 39.00
)
[10] => Array
(
[code] => GG071
[sku] => Array
(
)
[desc] => Nubuck Mid-Cut Safety Boot
[description] => GG071, Nubuck Mid-Cut Safety Boot
[price] => 39.00
[qty] => 2
[totalprice] => 78.00
)
[11] => Array
(
[code] => GG070
[sku] => Array
(
)
[desc] => Nubuck Mid-Cut Safety Boot
[description] => GG070, Nubuck Mid-Cut Safety Boot
[price] => 39.00
[qty] => 2
[totalprice] => 78.00
)
[12] => Array
(
[code] => PK454
[sku] => Array
(
)
[desc] => Ladies Black Hiker Boot
[description] => PK454, Ladies Black Hiker Boot
[price] => 31.00
[qty] => 1
[totalprice] => 31.00
)
)
)
)
)
)
)
Now I want to loop through that array, as I want to re-convert it into my XML format, I am able to access the first level of the array and the orderitems -> item -> code where the client purchased one single item, but I am not able to loop inside deeper level where the client purchased more than one item (second array)
here is my code
foreach($array['data']['transaction'] as $transaction){
//echo $transaction['fields']['transactionid']."<br>";
//echo $transaction['orderitems']['item']['code']."<br>";
if(isset($transaction['orderitems']['item']['code'])){
echo $transaction['orderitems']['item']['code']."<br>";
} else {
foreach($transaction['orderitems']['item'] as $multi_item){
echo "<--- MULTI ---><br>";
//tried so many things and none has worked;
//like $multi_item['code'];
}
}
}
how to access the code of each item purchased by john doe?
You can access this data by filtering the array.
In PHP >= 5.5.0 you can make a search like this;
$key = array_search('John Doe', array_column($yourArray, 'cardholdersname'));
This method will return the array that matched given criteria.
http://php.net/manual/tr/function.array-search.php

Parsing The json decoded array in php

curl_setopt_array($ch, $curlConfig);
$result = curl_exec($ch);
curl_close($ch);
print_r($jsonobj); //this shows me the op as:
Array (
[0] =>
stdClass Object (
[businessId] => 6
[subscriptionId] => 6
[name] => Eazy Borehole Drillers Limited
[city] => Blantyre
[pin] => 3332
[region] => Southern Region
[area] => City Centre
[address] => P.O. Box 3332 Blantyre
[email] => eazybhd#yahoo.com
[website] => eazyboreholedrillers.com
[district] => Blantyre
[phonenumber] => 265999434445
[category] => 14
)
[1] =>
stdClass Object (
[businessId] => 7
[subscriptionId] => 7
[name] => Eazy Travel Limited
[city] => Blantyre
[pin] => 3332
[region] => Southern Region
[area] => City Centre
[address] => P.O. BOX 3332 Blantyre
[email] => eazytravell#yahoo.com
[website] => eazytravell.com
[district] => Blantyre
[phonenumber] => 265999434445
[category] => 15
)
[2] =>
stdClass Object (
[businessId] => 20
[subscriptionId] => 20
[name] => Malswitch
[city] => Blantyre
[pin] => 384
[region] => Southern Region
[area] => City Centre
[address] => PO Box 384
[email] => info#malswitch.com
[website] => www.malswitch.com
[district] => Blantyre
[phonenumber] => 01 820 414
[category] => 69
)
[3] =>
stdClass Object (
[businessId] => 21
[subscriptionId] => 21
[name] => Malawi Savings Bank
[city] => Blantyre
[pin] => 521
[region] => Southern Region
[area] => Cicty Centre
[address] => PO Box 521 PO Box 521
[email] => balaka#msb.mw
[website] => www.msb.mw
[district] => Blantyre
[phonenumber] => 01 831 016 / 01
[category] => 69
)
Now my question is how to take the inside values like [businessId],[subscriptionId] out of this so that i can use them in my html page.
you use this 'array->key'. example array->businessId;
$data = Array (
[0] =>
stdClass Object (
[businessId] => 6
[subscriptionId] => 6
[name] => Eazy Borehole Drillers Limited
[city] => Blantyre
[pin] => 3332
[region] => Southern Region
[area] => City Centre
[address] => P.O. Box 3332 Blantyre
[email] => eazybhd#yahoo.com
[website] => eazyboreholedrillers.com
[district] => Blantyre
[phonenumber] => 265999434445
[category] => 14
)
)
$data[0]->businessId;
$data[0]->subscriptionId;
Your JSON object contains objects itself, which you can access with ->. Try this:
$jsonobj = ...; // Fetch your JSON object
foreach($jsonobj as $item) {
echo $item->businessId; // 6
echo $item->subscriptionId; // 6
echo $item->city; // Blantyre
echo $item->area; // City Centre
}

php array_multisort not sorting my multidimensional array

Array
(
[0] => Array
(
[id] => 7
[workorder_id] => 27
[truck_id] => 4
[event_type] => 1
[location_id] =>
[location_name] => Billing Address
[address_address] => 123 Main Street
[address_city] => Montreal
[address_state] => QC
[address_zip] => A1A1A1
[address_country_id] => 1
[contact] => bob
[phone] => 555-555-555
[fax] => 555-555-555
[po] => 123131
[notes] =>
[appointment_from] => 2013-03-30 12:30:00
[appointment_to] => 2013-03-30 14:30:00
[crossdock] => 0
[status] => 1
)
[1] => Array
(
[id] => 8
[workorder_id] => 27
[truck_id] => 4
[event_type] => -1
[location_id] =>
[location_name] => Billing Address
[address_address] => 123 Main Street
[address_city] => Montreal
[address_state] => QC
[address_zip] => A1A1A1
[address_country_id] => 1
[contact] =>
[phone] => 555-555-555
[fax] =>
[po] =>
[notes] =>
[appointment_from] => 2013-04-04 06:00:00
[appointment_to] => 2013-04-04 12:00:00
[crossdock] => 0
[status] => 1
)
[2] => Array
(
[id] => 9
[workorder_id] => 27
[truck_id] => 4
[event_type] => 1
[location_id] =>
[location_name] => Billing Address
[address_address] => 123 Main Street
[address_city] => Montreal
[address_state] => QC
[address_zip] => A1A1A1
[address_country_id] => 2
[contact] => Jim Smith
[phone] => 555-555-555
[fax] => 555-555-555
[po] =>
[notes] =>
[appointment_from] => 2013-04-16 10:00:00
[appointment_to] => 2013-04-16 12:00:00
[crossdock] => 0
[status] => 1
)
)
Okay, so I have this array, lets call it $array.
I now have a function to sort multidimensional arrays by multiple keys.
function sort_multiple_keys($array,$key1,$key1_sort = SORT_DESC,$key2,$key2_sort = SORT_ASC){
$sort = array();
if(count($array) > 0){
foreach($array as $k=>$v) {
$first[$k] = $v[$key1];
$second[$k] = $v[$key2];
}
array_multisort($first, $key1_sort, $second, $key2_sort, $array);
}
unset($sort);
}
So, I would to sort it by the EVENT TYPE and then APPOINTMENT_FROM date. So I run this function:
sort_multiple_keys($array,'event_type',SORT_DESC,'appointment_from',SORT_ASC);
But nothing??
Any help?
You're not actually returning a value from your sort function.
You can either return $array at the end; or pass it in as a reference, so the function works on the original instance instead of a copy; for that, you need to change the function definition to:
function sort_multiple_keys(&$array,$key1,$key1_sort = SORT_DESC,$key2,$key2_sort = SORT_ASC){
^ tells PHP that this variable is by reference

Categories