Home > OS >  How to get nested key values in Laravel
How to get nested key values in Laravel

Time:10-30

Can someone please tell me how to echo or use nested key values. I basically get() this collection and I'm using foreach to do some further calculations. My relation structure is zone.shipping and here I want to obtain fuel and emergency from the nest.

[{"id":614,"weight":"25.000","rate":"150.640","unit":"kg","detail":"normal","zone":{"id":5,"zone":"e","company":1,"shipping":{"id":1,"company":"fedex","fuel":"19.50","emergency":"1.35","source":1}}},

{"id":1838,"weight":"25.000","rate":"179.610","unit":"kg","detail":"normal","zone":{"id":17,"zone":"7","company":2,"shipping":{"id":2,"company":"dhl","fuel":"19.75","emergency":"0.50","source":1}}},

{"id":2414,"weight":"25.000","rate":"263.320","unit":"kg","detail":"normal","zone":{"id":24,"zone":"6","company":3,"shipping":{"id":3,"company":"ups","fuel":"24.00","emergency":"1.30","source":1}}}]

CodePudding user response:

You are looking for data_get()

CodePudding user response:

Take your array in one variable just I had taken for reference

$data = [{"id":614,"weight":"25.000","rate":"150.640","unit":"kg","detail":"normal","zone":{"id":5,"zone":"e","company":1,"shipping":{"id":1,"company":"fedex","fuel":"19.50","emergency":"1.35","source":1}}},

{"id":1838,"weight":"25.000","rate":"179.610","unit":"kg","detail":"normal","zone":{"id":17,"zone":"7","company":2,"shipping":{"id":2,"company":"dhl","fuel":"19.75","emergency":"0.50","source":1}}},

{"id":2414,"weight":"25.000","rate":"263.320","unit":"kg","detail":"normal","zone":{"id":24,"zone":"6","company":3,"shipping":{"id":3,"company":"ups","fuel":"24.00","emergency":"1.30","source":1}}}];

For fetch value

foreach($data as $key => $value)
{
   $fuel[] = $value['zone']['shipping']['fuel'];
   $emergency[] = $value['zone']['shipping']['emergency'];
}

Main thing how you can get fuel and emergency is

$value['zone']['shipping']['fuel'];
$value['zone']['shipping']['emergency'];

For specific index also you can get as:

$data[0]['zone']['shipping']['fuel'];
$data[0]['zone']['shipping']['emergency'];
  • Related