Search code examples
phparraysmultidimensional-arrayindexingarray-key

PHP: Multidimensional array, multidimensional keys?


$products = array(
  'paper' => "Paper Section" => array
  (
    'copier' => "Copier and Multipurpose",
    'inkjet' => "Inkjet Printer",
  ),
  'pens' => "Pen Section" => array
  (
    'ball' => "Ballpoint Pens",
    'hilite' => "Highlighters"
  ),
  'misc' => "Miscellaneous Section" => array
  (
    'tape' => "Sticky Tape",
    'glue' => "Adhesive"
  )
);

echo "<pre>";
foreach ($products as $section => $items)
  foreach ($items as $key => $value)
    echo "$section:\t$key\t($value)<br />";
echo "</pre>";

Obviously what I'm trying to do here is assign indexes to the $section set, and I'm getting errors for trying to do that. Is there another way to do it, or is it just not possible in PHP?


Solution

  • $products = array(
      'paper' => array(
        'title' => "Paper Section",
        'copier' => "Copier and Multipurpose",
        'inkjet' => "Inkjet Printer"
      )
    );   
    

    Something like the above, for instance. Another option is adding another dimension:

    $products = array(
      'paper' => array(
        'meta' => array(
            'title' => "Paper Section"
        ),
        'data' => array(
            'copier' => "Copier and Multipurpose",
            'inkjet' => "Inkjet Printer"
        )
      )
    );