user_1234
user_1234

Reputation: 131

Print multidimensional array using php , array stored in associative format

I am learning php, while practising I had an issue. I have created a multidimensional array with item values and am using a for loop to print those values but I am getting

Error: undefined offset

The array format is associative.

Requirement:

1) print all values using for loop/foreach loop

2) if any associative array is empty avoid that

3) check whether it is array or single value like some values again have their own array

$item_list=array();  //multidimensional array with associative values
echo '<pre>';print_r($item_list);

Array
(
    [total_price] => 1200
    [item_1] => Array
        (
            [item_name1] => xyz
            [item_price1] => 100.00

        )

    [item_2] => Array
        (
            [item_name2] => abc
            [item_price2] => 200.00

        )


    [item_3] => 
    [item_4] => Array
        (
            [item_name3] => aaa
            [item_price3] => 402.00
        )

)

// code which I have used to echo all values

for ($row = 0; $row < count($item_list); $row++) {
  // if value contain array then go to nested for loop else print direct value
  echo "<ul>";
  for ($col = 0; $col < count($item_list[$row]); $col++) {

    //echo "<li>".$item_list[$row][$col]."</li>";
    echo "<li>".array_values($item_list[$row])[$col]."</li>";

  }
  echo "</ul>";
}

Upvotes: 2

Views: 56

Answers (1)

Nick
Nick

Reputation: 147146

Since your array is associative, you can't access the values using a numeric index in a for loop. Instead, use a foreach loop over the elements:

foreach ($item_list as $key => $item_details) {
    if (is_array($item_details)) {
        echo "$key:\n";
        foreach ($item_details as $name => $value) {
            echo "\t$name: $value\n";
        }
    }
    else {
        echo "$key: $item_details\n";
    }
}

Output:

total_price: 1200
item_1:
    item_name1: xyz
    item_price1: 100
item_2:
    item_name2: abc
    item_price2: 200
item_3: 
item_4:
    item_name3: aaa
    item_price3: 402

Demo on 3v4l.org

Note it's not really clear what you're trying to achieve formatting wise, so I've just left the output in simple line format. It would be fairly easy to add <ul>/<li> structure to this.

Upvotes: 1

Related Questions