0

How to foreach through a deeper array in PHP? I want to approach 'price' and list all prices below each other.

$addons = get_product_addons($product->get_id());

When I VAR_DUMP the $addons var, it outputs the below.

array(1) {
  [0]=>
  array(7) {
    ["name"]=>
    string(8) "Afmeting"
    ["description"]=>
    string(0) ""
    ["type"]=>
    string(6) "select"
    ["position"]=>
    int(0)
    ["options"]=>
    array(10) {
      [0]=>
      array(5) {
        ["label"]=>
        string(8) "70 x 200"
        ["price"]=>
        string(0) "70.00"
        ["min"]=>
        string(0)""
...

So I want to output this result:

70.00

60.00

Etcetera.. *All prices

2 Answers 2

3

I guess that piece of code is what you are looking for:

foreach($addons as $addon)
{
   echo $addon["options"]["price"].PHP_EOL;
}

You do not need to use foreach to access nested elements of array. Just use it's key. PHP_EOL is a constant containing newline for your OS. For web application use special formatting suitable for your page (<br> e.g.)

Sign up to request clarification or add additional context in comments.

Comments

1

You can walk or foreach through the items:

<?php

$data =
[
    [
        'name' => 'orange',
        'options' =>
            [
                'price' => '6.00'
            ]
    ],
    [
        'name' => 'banana',
        'options' =>
            [
                'price' => '4.00'
            ]
    ]
];


array_walk($data, function($v) {
    echo $v['options']['price'], "\n";
});

Output:

6.00
4.00

Or you could create an array of prices and iterate on that (here using short function syntax):

$prices = array_map(fn($v)=>$v['options']['price'], $data);
var_export($prices);

Output:

array (
    0 => '6.00',
    1 => '4.00',
  )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.