简体   繁体   中英

How to echo data from a Multi-Dimensional Array in PHP?

I need to echo/return the data to the page like this:

Catalog: 251-2010
Gauge: 20g
Length: 10cm
Tip Size: 10mm

Here is the array called $vararray. It contains several different arrays of product variation data:

array(3) { 
    [0]=> array(1) { 
        ["251-2010"]=> array(1) { 
            ["Gauge"]=> string(3) "20g" 
        } 
    } 
    [1]=> array(1) { 
        ["251-2010"]=> array(1) { 
            ["Length"]=> string(4) "10cm" 
        } 
    } 
    [2]=> array(1) { 
        ["251-2010"]=> array(1) { 
            ["Tip Size"]=> string(4) "10mm" 
        } 
    } 
}
array(3) { 
    [0]=> array(1) { 
        ["600-VR1620"]=> array(1) { 
            ["Chart Type"]=> string(14) "Shirt" 
        } 
    } 
    [1]=> array(1) { 
        ["600-VR1152"]=> array(1) { 
            ["Chart Type"]=> string(13) "Trousers" 
        } 
    } 
    [2]=> array(1) { 
        ["600-VR16211"]=> array(1) { 
            ["Chart Type"]=> string(13) "Socks" 
        } 
    } 
}

I need something like this:

$vargroup = array();

foreach ($vararray as $vitems) {

    $varmeta = array_values($vararray);

    foreach ($varmeta as $metain => $vardetails) {
  
        vargroup[$metain]['catalog'] = $vardetails['Catalog'];
        vargroup[$metain]['gauge'] = $vardetails['Gauge'];
        vargroup[$metain]['length'] = $vardetails['Length'];
        vargroup[$metain]['tipsize'] = $vardetails['Tip Size'];

    }
    $vars_profile = '';
    foreach ($vargroup as $vgrp) {
        $vars_profile .= $vgrp[catalog] . '<br>' . $vgrp[gauge] . '<br>' . $vgrp[length] . '<br>' . $vgrp[tipsize];
    }
    return $vars_profile;
}

I'm having a lot of trouble getting it right.

You can't get all of Catalog , Gauge , Length , and Tip Size from the same $vardetails element, they're in different elements of the array. You need to drill into each element to get its key and value.

You can create $vars_profile in the loop that's processing the original array, you don't need $vargroup .

$vars_profile = '';

foreach ($vararray as $vitems) {
    foreach ($vitems as $metain => $vardetails) {
        $vars_profile = "Catalog: $metain<br>";
        foreach ($vardetails as $key => $value) {
            $vars_profile = "$key: $value</br>";
        }
    }
}

return $vars_profile;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM