Using array_chunk on multi array - php
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;
}
Related
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
Loop a multidimensional array
I have a multidimensional array and I want access and loop through with a foreach loop. I need to support to access to following items: -deliveryMethod -totalPrice -preparationTime -[shipping][email] -[notes] => Email: Array ( [page] => 1 [page_size] => 10 [total] => 3 [num_pages] => 1 [result] => Array ( [0] => Array ( [_id] => 58c9954070f15c0011535f4d [friendlyID] => 460 [date] => 1489605952453 [status] => STATUS_DELIVERED [deliveryMethod] => METHOD_TAKEAWAY [notes] => [grandTotal] => 75.56 [application] => 58be7dc51fa4bc00111b9a64 [__v] => 0 [items] => Array ( [0] => Array ( [_id] => 58c9954070f15c0011535f4e [totalPrice] => 75.56 [preparationTime] => 10 [unitPrice] => 18.89 [quantity] => 4 [name] => Calabrese 29cm [tax] => Array ( [value] => 23 [percentage] => 0.23 ) ) ) [shipping] => Array ( [phone] => 32423432 [email] => info#lovanet.ch [country] => [city] => [zip] => [fullname] => lori ) [restaurant] => Array ( [notes] => Email: info#lovanet.ch [country] => [city] => [zip] => [address] => Hauptstrasse 43a Bronschhofen [name] => Restaurant Würe ) ) [1] => Array ( [_id] => 58c9948170f15c0011535f4a [friendlyID] => 459 [date] => 1489605761859 [status] => STATUS_SHIPPED [deliveryMethod] => METHOD_TAKEAWAY [notes] => [grandTotal] => 54.68 [application] => 58be7dc51fa4bc00111b9a64 [__v] => 0 [items] => Array ( [0] => Array ( [_id] => 58c9948170f15c0011535f4c [totalPrice] => 12.9 [preparationTime] => 10 [unitPrice] => 12.9 [quantity] => 1 [name] => Calabrese 22cm [tax] => Array ( [value] => 23 [percentage] => 0.23 ) ) [1] => Array ( [_id] => 58c9948170f15c0011535f4b [totalPrice] => 41.78 [preparationTime] => 10 [description] => Extra Salami- $2.00 [unitPrice] => 18.89 [quantity] => 2 [name] => Calabrese 29cm [tax] => Array ( [value] => 23 [percentage] => 0.23 ) ) ) [shipping] => Array ( [phone] => 32423432 [email] => info#lovanet.ch [country] => [city] => [zip] => [fullname] => lori ) [restaurant] => Array ( [notes] => Email: info#lovanet.ch [country] => [city] => [zip] => [address] => Hauptstrasse 43a Bronschhofen [name] => Restaurant Würe ) ) [2] => Array ( [_id] => 58be912e1fa4bc00111b9ae6 [friendlyID] => 443 [date] => 1488884014509 [status] => STATUS_IN_PROGRESS [deliveryMethod] => METHOD_TAKEAWAY [notes] => [grandTotal] => 12.9 [application] => 58be7dc51fa4bc00111b9a64 [__v] => 0 [items] => Array ( [0] => Array ( [name] => Calabrese 22cm [quantity] => 1 [unitPrice] => 12.9 [preparationTime] => 10 [totalPrice] => 12.9 [_id] => 58be912e1fa4bc00111b9ae7 [tax] => Array ( [percentage] => 0.23 [value] => 23 ) ) ) [shipping] => Array ( [fullname] => lori [zip] => [city] => [country] => [email] => info#lovanet.ch [phone] => 32423432 ) [restaurant] => Array ( [name] => Restaurant Würe [address] => Hauptstrasse 43a Bronschhofen [zip] => [city] => [country] => [notes] => Email: info#lovanet.ch ) ) ) ) Could you please help me to create this foreach loop?
foreach ($myArrayName['result'] as $entry) { foreach ($myArrayName['items'] as $item) { echo 'totalPrice: ' . $item['totalPrice'] . '<br />'; echo 'preparationTime: ' . $item['preparationTime'] . '<br />'; } echo 'deliveryMethod:' . $entry['deliveryMethod'] . '<br />'; echo 'E-Mail: ' . $entry['shipping']['email'] . '<br />'; echo 'E-Mail 2: ' . substr($entry['restaurant']['notes'], 7) . '<br />'; } try this code and replace $myArrayName with the name of your array
How to insert a new values pair in an associative array in PHP?
I've an associative array. I am attempting to create each sub array within a loop and insert it into a multidimensional array. Google suggested using array_merge, but after using 'print_r' on the multidimensional array with the code below, only the last sub-array is being displayed. Array ( [data] => Array ( [0] => Array ( [candidate] => Array ( [id] => 184 [firstName] => skg [lastName] => s [address] => Array ( [address1] => sakthi [address2] => [city] => [state] => [zip] => [countryID] => 1 [countryName] => United States [countryCode] => US ) [hourlyRate] => 0 ) [jobOrder] => Array ( [id] => 88 [title] => Tech Analyst ) ) [1] => Array ( [candidate] => Array ( [id] => 852 [firstName] => mso cool [lastName] => [address] => Array ( [address1] => [address2] => [city] => [state] => [zip] => [countryID] => 1 [countryName] => United States [countryCode] => US ) [hourlyRate] => 0 ) [jobOrder] => Array ( [id] => 57 [title] => Tester ) ) And Another Array like this : [rating] => Array ( [0] => 7 [1] => 5 [2] => ) How to get merge this array value into previous array values like Array ( [data] => Array ( [0] => Array ( [candidate] => Array ( [id] => 184 [firstName] => skg [lastName] => s [address] => Array ( [address1] => sakthi [address2] => [city] => [state] => [zip] => [countryID] => 1 [countryName] => United States [countryCode] => US ) [hourlyRate] => 0 [rating] => 7 ) [jobOrder] => Array ( [id] => 88 [title] => Tech Analyst ) ) [1] => Array ( [candidate] => Array ( [id] => 852 [firstName] => mso cool [lastName] => [address] => Array ( [address1] => [address2] => [city] => [state] => [zip] => [countryID] => 1 [countryName] => United States [countryCode] => US ) [hourlyRate] => 0 [rating] => 5 ) [jobOrder] => Array ( [id] => 57 [title] => Tester ) ) I tried lot of tricks but couldn't get the desired array format. Can any one help me in this to get the desired array? Thanks in advance.
$arr = array(); //filled with data $rating = array(); //filled with rates foreach ( $rating as $key =>$rate ) { $arr['data'][ $key ]['rating'] = $rate; }
<?php $arr=Array( 'data'=>Array( 0=>Array('candidate'=>Array()), 1=>Array('candidate'=>Array()) ) ); $rating=Array(7,5); foreach($rating as $key=>$val){ $arr['data'][$key]['rating']=$val; } print_r($arr); Returns: Array ( [data] => Array ( [0] => Array ( [candidate] => Array ( ) [rating] => 7 ) [1] => Array ( [candidate] => Array ( ) [rating] => 5 ) ) )
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 }
how to retrive all object array with one value?
This question is a follow up from this Now for my follow up question I also have this object on page: Array ( [registrants] => Array ( [0] => Registrant Object ( [title] => D C [link] => ********** [id] => *************** [updated] => 2013-03-06T12:11:49-05:00 [lastName] => C [firstName] => D [email] => ********* [personalInformation] => PersonalInformation Object ( [cellPhone] => [label] => [addr1] => [addr2] => [addr3] => [city] => [state] => [postalCode] => [province] => [country] => [phone] => ) [businessInformation] => BusinessInformation Object ( [fax] => [website] => [blog] => [company] => [jobTitle] => [department] => [label] => [addr1] => [addr2] => [addr3] => [city] => [state] => [postalCode] => [province] => [country] => [phone] => ) [customInformation1] => Array ( ) [customInformation2] => Array ( ) [registrationStatus] => REGISTERED [registrationDate] => 2013-03-06T12:11:49-05:00 [guestCount] => 0 [paymentStatus] => NA [orderAmount] => [currencyType] => [paymentType] => [costs] => Array ( ) ) [1] => Registrant Object ( [title] => Test Test [link] => **** [id] => ************* [updated] => 2013-03-06T12:47:47-05:00 [lastName] => Test [firstName] => Test [email] => *************** [personalInformation] => PersonalInformation Object ( [cellPhone] => [label] => [addr1] => [addr2] => [addr3] => [city] => [state] => [postalCode] => [province] => [country] => [phone] => ) [businessInformation] => BusinessInformation Object ( [fax] => [website] => [blog] => [company] => [jobTitle] => [department] => [label] => [addr1] => [addr2] => [addr3] => [city] => [state] => [postalCode] => [province] => [country] => [phone] => ) [customInformation1] => Array ( ) [customInformation2] => Array ( ) [registrationStatus] => REGISTERED [registrationDate] => 2013-03-06T12:47:47-05:00 [guestCount] => 0 [paymentStatus] => NA [orderAmount] => [currencyType] => [paymentType] => [costs] => Array ( ) ) ) [nextLink] => ) So following the same theory I am retriving the values like this: <?php echo $Registrant->lastName; echo $Registrant->firstName; echo $Registrant->email; ?> but this only retrieves the first lastname and firstname from [0] => Registrant Object not from 1 => Registrant Object how to i get all of the first names and last names? Thank everyone for there interest and there time. Kind regards Chris
To explain your scenario a bit further than other answers. You have an array of (Registrant) objects here. This is actually an associative array (as all PHP arrays) with indices from 0 - 1. $registrantObjects[0] // would give first Registrant object $registrantObjects[1] // would give second Registrant object You can access them both. But if you want to iterate the array (i.e. going over all elements and do the same for each one), you should use a loop. PHP has a nice foreach loop for this use case: foreach ($registrantObjects as $registrant) { // $registrant is a Registrant object here echo $registrant->lastName; } You could also try this: foreach ($registrantObjects as $index => $registrant) { // $registrant is a also Registrant object here // But we have a variable $index, too. It represents the current 'key' // We have a normal (numbered) array thus the keys are [0..1] echo $registrant->lastName; } And both loops are equal to this for loop: for ($i = 0, $len = count($registrantObjects); $i < $len; $i++) { // $registrantObjects[$i] gives a Registrant object }
Lets say the object you printed is "$RegistrantObjects" You can do the following thing : foreach ($RegistrantObjects as $registrant) { echo $registrant->lastName; } Within the foreach, the $registrant object will be accessible the same way that you code accesses it.
Try the below code; <?php foreach($Registrant as $reg) { echo $reg->firstname; echo $reg->lastname; } ?>