Looping in a complex array - php

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

Related

sort array based on the indents

I have the current array in PHP which is being extracted from a MySQL database (PDO fetch all);
[0] => Array
(
[id] => 78
[indent] => 2.2
[partnumber] => OPPN-39-596
[description] => BACK WASH NOZZLE - 32 DIA
[size] =>
[rev] => A
[code] => MCH
[quantity] => 1
[total] => 1
[notes] =>
[partcost] =>
[totalcost] =>
)
[1] => Array
(
[id] => 23
[indent] => 2.3
[partnumber] => OPPN-21-508
[description] => FRONT 12MM JET ASSY
[size] =>
[rev] => A
[code] => ASY
[quantity] => 3
[total] => 3
[notes] =>
[partcost] =>
[totalcost] =>
)
[2] => Array
(
[id] => 17
[indent] => 2.3.1
[partnumber] => OPPN-21-356
[description] => INTERNAL CIRCLIP Ø42 BORE S/S
[size] =>
[rev] =>
[code] => HRD
[quantity] => 1
[total] => 3
[notes] =>
[partcost] =>
[totalcost] =>
)
[3] => Array
(
[id] => 26
[indent] => 2.3.2
[partnumber] => OPPN-21-509
[description] => FRONT JET 12MM NOZZLE
[size] =>
[rev] => A
[code] => MCH
[quantity] => 1
[total] => 3
[notes] =>
[partcost] =>
[totalcost] =>
)
[4] => Array
(
[id] => 28
[indent] => 2.3.3
[partnumber] => OPPN-21-510
[description] => FLOW STRAIGHTENER 12MM INSERT 1
[size] =>
[rev] => A
[code] => MCH
[quantity] => 1
[total] => 3
[notes] =>
[partcost] =>
[totalcost] =>
)
[5] => Array
(
[id] => 30
[indent] => 2.3.4
[partnumber] => OPPN-21-511
[description] => FLOW STRAIGHTENER 12MM INSERT 2
[size] =>
[rev] => A
[code] => MCH
[quantity] => 1
[total] => 3
[notes] =>
[partcost] =>
[totalcost] =>
)
[6] => Array
(
[id] => 34
[indent] => 2.3.5
[partnumber] => OPPN-21-524
[description] => O RING 3.53 X 32.92 ID NITRILE
[size] =>
[rev] => A
[code] => HRD
[quantity] => 1
[total] => 3
[notes] =>
[partcost] =>
[totalcost] =>
)
[7] => Array
(
[id] => 76
[indent] => 2.4
[partnumber] => OPPN-39-592
[description] => FRONT 14MM JET ASSY
[size] =>
[rev] => A
[code] => ASY
[quantity] => 10
[total] => 10
[notes] =>
[partcost] =>
[totalcost] =>
)
[8] => Array
(
[id] => 67
[indent] => 2.4.1
[partnumber] => OPPN-39-581
[description] => FRONT JET 14MM NOZZLE
[size] =>
[rev] => A
[code] => MCH
[quantity] => 1
[total] => 10
[notes] =>
[partcost] =>
[totalcost] =>
)
I need to come up with some code to convert the array to this;
[0] => Array
(
[id] => 78
[indent] => 2.2
[partnumber] => OPPN-39-596
[description] => BACK WASH NOZZLE - 32 DIA
[size] =>
[rev] => A
[code] => MCH
[quantity] => 1
[total] => 1
[notes] =>
[partcost] =>
[totalcost] =>
)
[1] => Array
(
[id] => 23
[indent] => 2.3
[partnumber] => OPPN-21-508
[description] => FRONT 12MM JET ASSY
[size] =>
[rev] => A
[code] => ASY
[quantity] => 3
[total] => 3
[notes] =>
[partcost] =>
[totalcost] =>
[0] => Array
(
[id] => 17
[indent] => 2.3.1
[partnumber] => OPPN-21-356
[description] => INTERNAL CIRCLIP Ø42 BORE S/S
[size] =>
[rev] =>
[code] => HRD
[quantity] => 1
[total] => 3
[notes] =>
[partcost] =>
[totalcost] =>
)
[1] => Array
(
[id] => 26
[indent] => 2.3.2
[partnumber] => OPPN-21-509
[description] => FRONT JET 12MM NOZZLE
[size] =>
[rev] => A
[code] => MCH
[quantity] => 1
[total] => 3
[notes] =>
[partcost] =>
[totalcost] =>
)
[2] => Array
(
[id] => 28
[indent] => 2.3.3
[partnumber] => OPPN-21-510
[description] => FLOW STRAIGHTENER 12MM INSERT 1
[size] =>
[rev] => A
[code] => MCH
[quantity] => 1
[total] => 3
[notes] =>
[partcost] =>
[totalcost] =>
)
[3] => Array
(
[id] => 30
[indent] => 2.3.4
[partnumber] => OPPN-21-511
[description] => FLOW STRAIGHTENER 12MM INSERT 2
[size] =>
[rev] => A
[code] => MCH
[quantity] => 1
[total] => 3
[notes] =>
[partcost] =>
[totalcost] =>
)
[4] => Array
(
[id] => 34
[indent] => 2.3.5
[partnumber] => OPPN-21-524
[description] => O RING 3.53 X 32.92 ID NITRILE
[size] =>
[rev] => A
[code] => HRD
[quantity] => 1
[total] => 3
[notes] =>
[partcost] =>
[totalcost] =>
)
)
[2] => Array
(
[id] => 76
[indent] => 2.4
[partnumber] => OPPN-39-592
[description] => FRONT 14MM JET ASSY
[size] =>
[rev] => A
[code] => ASY
[quantity] => 10
[total] => 10
[notes] =>
[partcost] =>
[totalcost] =>
[0] => Array
(
[id] => 67
[indent] => 2.4.1
[partnumber] => OPPN-39-581
[description] => FRONT JET 14MM NOZZLE
[size] =>
[rev] => A
[code] => MCH
[quantity] => 1
[total] => 10
[notes] =>
[partcost] =>
[totalcost] =>
)
)
[3] => Array
(
[id] => 76
[indent] => 2.5
[partnumber] => OPPN-39-592
[description] => FRONT 14MM JET ASSY
[size] =>
[rev] => A
[code] => ASY
[quantity] => 10
[total] => 10
[notes] =>
[partcost] =>
[totalcost] =>
)
The array element with an indent of 2.3.1 becomes a child element of the element which has an indent of 2.3 and so on... I need to come up with some code that automatically formats this array to way I need it. I have fighting with multi dimensional for loops all day now but had no luck. Any guidance and assistance would be appreciated.
I have created snippet strongly coupled for your requirement, have a look.
$result = [];
foreach ($inputArr as $key => $value) {
$indentArr = explode('.', $value['indent']);
if (count($indentArr) == 2) {
$result[$value['indent']] = $value;
} else {
unset($indentArr[2]);
$parentIndent = implode('.',$indentArr);
$result[$parentIndent][] = $value;
}
}
Demo.
I have put together this code which will work as long as your top level is always "x.x", for example "1.0" and not just "1" , I then tested it using your given data as $values variable. Hope this helps.
//An array for all the grouped elements
$grouped = array();
foreach( $values as $key=>$properties ){
//Get the first two figures (and D.P) of the indent
$indent = substr( $properties['indent'], 0, 3 );
//Does this indent number already exist in the
if( !in_array( $indent, array_keys( $grouped ) ) ){
//Create a new parent element
$grouped[ $indent ] = $properties;
} else {
//Create a new child element
$grouped[ $indent ][] = $properties;
}
}
//Replace indent keys with numeric keys
$grouped = array_values( $grouped );
//Display
echo '<pre>' . print_r( $grouped, 1 ) . '</pre>';

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

How can i sort array in php

Please let me know how can sort array with one column line_total descending format. I want that array in line_total descending format bcoz i want to display data upper sale to lower sale. So please help me.
Array
(
[totalusers] => 1
[TranReport] => Array
(
[start] => 01-01-2017
[end] => 31-12-2017
)
[webhits] => 794
[paypal] => Yes
[cash] => No
[Transactions] => Array
(
[0] => Array
(
[order_date] => 03-02-2017
[customer_name] => Mohsin khan
[payment_method] => PayPal
[product_list] => Array
(
[0] => Array
(
[product_name] => USB Cable – Iphone → 1M USB Cable - Iphone
[qty] => 1
[line_total] => 9
)
[1] => Array
(
[product_name] => USB Cable – Iphone → 2M USB Cable - Iphone
[qty] => 2
[line_total] => 24
)
)
[quantity] => 3
[order_currency] => USD
[order_total] => 48.00$
[new_total] => 48.00
)
[1] => Array
(
[order_date] => 09-01-2017
[customer_name] => Mohsin khan
[payment_method] => PayPal
[product_list] => Array
(
[0] => Array
(
[product_name] => AA USB Charger
[qty] => 1
[line_total] => 15
)
[1] => Array
(
[product_name] => Car Charger - Dual USB - Low Profile
[qty] => 1
[line_total] => 15
)
[2] => Array
(
[product_name] => Mister Hose → 20m Mister Hose
[qty] => 1
[line_total] => 20
)
)
[quantity] => 3
[order_currency] => USD
[order_total] => 50.00$
[new_total] => 50.00
)
[2] => Array
(
[order_date] => 07-01-2017
[customer_name] => Mohsin khan
[payment_method] => PayPal
[product_list] => Array
(
[0] => Array
(
[product_name] => Quick Charge V3 - Dual USB - Car Charger
[qty] => 1
[line_total] => 15
)
[1] => Array
(
[product_name] => Car Charger - Dual USB - Low Profile
[qty] => 1
[line_total] => 15
)
[2] => Array
(
[product_name] => Mister Hose → 20m Mister Hose
[qty] => 1
[line_total] => 20
)
)
[quantity] => 1
[order_currency] => USD
[order_total] => 15.00$
[new_total] => 15.00
)
)
[deliveytotal] => 0
)
You need to use usort function http://php.net/manual/en/function.uksort.php . The rest is just my interpretation of what you want to achieve - sort transactions by sum of line_total in products
$array = []; //your array
function sumLinesTotal($product_list) {
return array_sum(array_map($product_list, function($product){
return $product['line_total'];
});
}
usort($array['Transactions'], function ($a, $b) {
return sumLinesTotal($a) < sumLinesTotal($b);
});

Multidimensional Array Merging

I have an array that looks like this:
Array
(
[0] => Array
(
[ASINS] => Array
(
[0] => B0000714BR
[1] => B0002F6BT2
[2] => B000Y11B7G
[3] => B00571IMWK
[4] => 0767827716
)
[Product] => Array
(
[0] => Array
(
[Title] => The Best Little Whorehouse in Texas
[UPC] => 025192022029
[ASIN] => B0000714BR
[SalesRank] => 13104
[ImageURL] => http://ecx.images-amazon.com/images/I/51E0DAT5E8L._SL200_.jpg
[ProductGroup] => DVD
[Publisher] => Universal Studios
[NumberOfDiscs] => 1
[LowestPrice] => 2.91
[ShippingPrice] => 3.99
[TotalPrice] => 6.9
)
[1] => Array
(
[Title] => Are You Being Served? Again! (The Complete Series)
[UPC] => 794051202420
[ASIN] => B0002F6BT2
[SalesRank] => 13118
[ImageURL] => http://ecx.images-amazon.com/images/I/61JAD7WAT0L._SL200_.jpg
[ProductGroup] => DVD
[Publisher] => BBC Home Entertainment
[NumberOfDiscs] => 2
[LowestPrice] => 10.99
[ShippingPrice] => 3.99
[TotalPrice] => 14.98
)
[2] => Array
(
[Title] => Homeward Bound - The Incredible Journey / Homeward Bound II - Lost In San Francisco
[UPC] => 786936758320
[ASIN] => B000Y11B7G
[SalesRank] => 2145
[ImageURL] => http://ecx.images-amazon.com/images/I/61bMYabUQkL._SL200_.jpg
[ProductGroup] => DVD
[Publisher] => Walt Disney Home Entertainment
[NumberOfDiscs] => 2
[LowestPrice] => 19.95
[ShippingPrice] => 0.00
[TotalPrice] => 19.95
)
[3] => Array
(
[Title] => Joy Ride / Joy Ride 2: Dead Ahead (Two-Pack)
[UPC] => 024543647058
[ASIN] => B00571IMWK
[SalesRank] => 113077
[ImageURL] => http://ecx.images-amazon.com/images/I/5169VAQVGZL._SL200_.jpg
[ProductGroup] => DVD
[Publisher] => 20th Century Fox
[NumberOfDiscs] => 2
[LowestPrice] => 6.49
[ShippingPrice] => 3.99
[TotalPrice] => 10.48
)
[4] => Array
(
[Title] => Christine
[UPC] => 043396016194
[ASIN] => 0767827716
[SalesRank] => 40140
[ImageURL] => http://ecx.images-amazon.com/images/I/510A99AQWHL._SL200_.jpg
[ProductGroup] => DVD
[Publisher] => Sony Pictures Home Entertainment
[NumberOfDiscs] => 1
[LowestPrice] => 2.81
[ShippingPrice] => 3.99
[TotalPrice] => 6.8
)
)
)
[1] => Array
(
[ASINS] => Array
(
[0] => B00005JPH2
[1] => B00006JMRE
[2] => B000U1ZV7G
[3] => B00004RJ71
[4] => B00008977G
)
[Product] => Array
(
[0] => Array
(
[Title] => The Chronicles of Narnia: Prince Caspian
[UPC] => 786936735437
[ASIN] => B00005JPH2
[SalesRank] => 2848
[ImageURL] => http://ecx.images-amazon.com/images/I/618uTYKkadL._SL200_.jpg
[ProductGroup] => DVD
[Publisher] => Walt Disney Studios Home Entertainment
[NumberOfDiscs] => 1
[LowestPrice] => 6.62
[ShippingPrice] => 0.00
[TotalPrice] => 6.62
)
[1] => Array
(
[Title] => High Noon (Collector's Edition)
[UPC] => 017153125719
[ASIN] => B00006JMRE
[SalesRank] => 99262
[ImageURL] => http://ecx.images-amazon.com/images/I/51fPYWpMqaL._SL200_.jpg
[ProductGroup] => DVD
[Publisher] => Republic Pictures
[NumberOfDiscs] => 1
[LowestPrice] => 3.26
[ShippingPrice] => 3.99
[TotalPrice] => 7.25
)
[2] => Array
(
[Title] => 4 Film Favorites: Draculas (Dracula A.D. 1972, Dracula Has Risen from the Grave, Horror of Dracula, Taste the Blood of Dracula)
[UPC] => 085391174264
[ASIN] => B000U1ZV7G
[SalesRank] => 14994
[ImageURL] => http://ecx.images-amazon.com/images/I/61CBLkwawNL._SL200_.jpg
[ProductGroup] => DVD
[Publisher] => Warner Home Video
[NumberOfDiscs] => 2
[LowestPrice] => 6.30
[ShippingPrice] => 0.00
[TotalPrice] => 6.3
)
[3] => Array
(
[Title] => Blood In, Blood Out
[UPC] => 717951008701
[ASIN] => B00004RJ71
[SalesRank] => 1862
[ImageURL] => http://ecx.images-amazon.com/images/I/51N7R17P51L._SL200_.jpg
[ProductGroup] => DVD
[Publisher] => Hollywood Pictures Home Entertainment
[NumberOfDiscs] => 1
[LowestPrice] => 1.37
[ShippingPrice] => 3.99
[TotalPrice] => 5.36
)
[4] => Array
(
[Title] => Gone Fishin'
[UPC] => 786936182576
[ASIN] => B00008977G
[SalesRank] => 13628
[ImageURL] => http://ecx.images-amazon.com/images/I/51XQ9YR8BML._SL200_.jpg
[ProductGroup] => DVD
[Publisher] => Walt Disney Video// Mill Creek
[NumberOfDiscs] => 1
[LowestPrice] => 3.96
[ShippingPrice] => 3.99
[TotalPrice] => 7.95
)
)
)
)
Maybe I am going about this the wrong way, but I am trying to merge the outer most arrays indexed [0] and [1]. The arrays are produced from an API query. The outer most arrays indexes could continue indefinitely. I am trying to combine them so I can loop through them using a for loop to produce a new element in the inner most product arrays based on the price and sales rank in each array.
I do not even know if this is possible but any help or even a push in the right direction would be greatly appreciated.
Thanks,
Eric
$result = $array[0];
for ($i = 1; $i < count($array); $i++) {
foreach ($result as $key => &$value) {
$value = array_merge($value, $array[$i][$key]);
}
}
Now $result should be an associative array that contains the merged contents of all the original sub-arrays.

array_unique wrongly discarding values

I'm trying to use array_unique to discard of repeated values.
Array
(
[0] => Array
(
[book_id] => 1203910329
[author] => Gauci, Joe
[description] => Paperback. Very Good.
[isbn] => 9781907374067
[publisher] =>
[date] =>
[currency] => USD
[price] => 10.97
[bookseller] => xx
[bookseller_location] => GBR
[condition] => 3
[shipping_ground] => 4.73
[shipping_expedited] => 6.33
)
[1] => Array
(
[book_id] => 12312314556
[author] => Gauci, Joe
[description] => Paperback. GOOD.
[isbn] => 9781907374067
[publisher] =>
[date] =>
[currency] => USD
[price] => 1.84
[bookseller] => xx
[bookseller_location] => GBR
[condition] => 2.5
[shipping_ground] => 4.73
[shipping_expedited] => 6.33
)
[2] => Array
(
[book_id] => 12312314556
[author] => Gauci, Joe
[description] => Paperback. GOOD.
[isbn] => 9781907374067
[publisher] =>
[date] =>
[currency] => USD
[price] => 1.84
[bookseller] => xx
[bookseller_location] => GBR
[condition] => 2.5
[shipping_ground] => 4.73
[shipping_expedited] => 6.33
)
)
every time I use array_unique($results) only the first value is returned
Array
(
[0] => Array
(
[book_id] => 1203910329
[author] => Gauci, Joe
[description] => Paperback. Very Good.
[isbn] => 9781907374067
[publisher] =>
[date] =>
[currency] => USD
[price] => 10.97
[bookseller] => xx
[bookseller_location] => GBR
[condition] => 3
[shipping_ground] => 4.73
[shipping_expedited] => 6.33
)
)
Where am I going with array_unique?
You can't use array_unique with nested arrays. The comparison used is clearly documented:
(string) $elem1 === (string) $elem2

Categories