简体   繁体   中英

Display multidimensional array dynamically

I have this array,

Array
(
[part_number] => Array
    (
        [1] => "88888"
        [2] => "898989"
        [3] => "12312"
        [4] => "321321321"
    )

[manufacturer] => Array
    (
        [1] => "Dell"
        [2] => "Toshiba"
        [3] => "Asus"
        [4] => "AMD"
    )

[description] => Array
    (
        [1] => "i3 Processor"
        [2] => "i5 Processor"
        [3] => "i7 Processor"
        [4] => "Video Card 4GB"
    )

[list_price] => Array
    (
        [1] => "450"
        [2] => "100"
        [3] => "100"
        [4] => "150"
    )

[net_price] => Array
    (
        [1] => "500"
        [2] => "120"
        [3] => "120"
        [4] => "200"
    )

[quantity] => Array
    (
        [1] => "600"
        [2] => "150"
        [3] => "150"
        [4] => "80"
    )

[measure] => Array
    (
        [1] => "14 inch"
        [2] => "Pc/s"
        [3] => "Pc/s"
        [4] => "Pc/s"
       )

   ) 

and I want to display it dynamically depending on the array values.

Sample format:

part_number : "88888"
manufacturer : "Dell"
description : "i3 Processor"
list_price : "450"
net_price : "500"
quantity : "600"
measure : "14 inch"

and so on…

I'm stuck in this part.

Here's my code

<?php foreach($success_arr as $success_part_number => $val): ?>
    <?=$success_part_number." : ".$val[1];?>
<?php endforeach; ?>

I want the val to be dynamic. I don't know how to count the number of values return in an array.

You an run the foreach loop inside for loop.

   $counter = count($array['manufacturer']);
        for ($i=0; $i < $counter; $i++) 
        { 
            echo "<ul>";
            foreach($array as $success_part_number => $val)
            {
                echo "<li>";
                echo $success_part_number." : ".$val[$i];
                echo "</li>";
            }
            echo "</ul>";
            echo "<hr>";
        }

You can nicely format your data in table like code bellow, but you have to make sure all inner arrays have the same length

echo '<table>';
// $i is your starting point - 1;
for($i = 0; $i<= count($arr['part_number']); $i++)
{
    foreach($arr as $k => $v)
    {
    // with first loop we build table headers => your inner array keys
        if($i==0) {
            echo '<th>' .$k. '</th>';
            continue;
        } 
        // start to build your data rows
        echo '<td>' . $v[$i] . '</td>';
    }
    echo '</tr>';
}
echo '</table>';

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