Yuko Pangestu Yuko Pangestu - 1 year ago 40
PHP Question

How to get Data from Nested Array [Laravel]

To the point, so in this question I want to embed Google Analytics Ecommerce tracking that has been needed for my company, in this case I have an array which is here

data_diri": [


"nama_pasien": "ahmad karim harahap",
"email_pasien": null,
"birth_date": "3",
"birth_month": "06",
"birth_year": "1965",
"gender": "1",
"alamat": "jalan jakarta",
"cit_code": "0",
"telp": "0211111",
"layanan": "1",
"home_service_date": "25",
"home_service_month": "05",
"home_service_year": "2016"


Sorry if there is an error with my json files but it was a valid json, so my question is how can I get the value of the child of "data_diri" value...

I am using return command from php e.g.

return $result;

and to get "data_diri" I use:

return $result[0]["data_diri"];

so how can I get the nested value of "data_diri"?
I am using

return $result[0]["data_diri"]["nama_pasien"];

but it doesn't return anything but error "undefined index: nama_pasien", is there any suggestion?


Answer Source

The data_diri is an array with items, so you need to run:

return $result[0]["data_diri"][0]["nama_pasien"];

This will return the first item in data_diri.

If there are more results in the data_diri you need to add a foreach loop if you don't want the first value.

Hope this works and choose the method you want to use!

Your next question

You can loop through the results like this:

First you need to return the results

return $result;

After that you can loop through all the data like this:

$data = new GoogleAnalytics(); //this is a controller
$result = $data->getData; //this is a method in the GoogleAnalytics Controller
foreach($results as $result) {
    dump($result); //this will dump the array
    foreach($result['data_diri'] as $data) {

This will dump all nama_pasien in the data_diri array.

Hope this works!