简体   繁体   English

从数组中提取数据(PHP)

[英]Pull Data From an Array (PHP)

I have created a simple order form that is selling a variety of cards. 我创建了一个简单的订单表格,可以出售各种卡。 These cards come in different colors. 这些卡有不同的颜色。 The code below shows the colors offered. 下面的代码显示了提供的颜色。 I need to be able to pull the data from the array below so that I can determine how many of each color did the user select on the form for ordering purposes. 我需要能够从下面的数组中提取数据,以便可以确定用户在订购时选择了每种颜色中的多少种。

Array
(
    [qty] => Array
        (
            ['red'] => 0
            ['blue'] => 0
            ['green'] => 0
            ['yellow'] => 0
            ['orange'] => 0
            ['white'] => 0
            ['black'] => 0
            ['purple'] => 0
            ['teal'] => 0
            ['grey'] => 0
        )

Any assistance with this I greatly appreciate. 我对此表示感谢。

Try something like this: 尝试这样的事情:

<?php
    $some_input = array('red','red','white');
    $a =array( 'qty' => array(
    'red' => 0,
    'blue' => 0,
    'green' => 0,
    'yellow' => 0,
    'orange' => 0,
    'white' => 0,
    'black' => 0,
    'purple' => 0,
    'teal' => 0,
    'grey' => 0,
));
    $f = function($x) use(&$a)
    {
        if(in_array($x, $a['qty']))
        {
            $a['qty'][$x]++;
        }
    };
    array_map($f, $some_input);

    var_dump($a);
?>

You can see the code running here click in the button paste 您可以看到此处运行的代码单击按钮粘贴

Do you just want to display the info on a page? 您是否只想在页面上显示信息?

If so, this should do the job for you (assuming your array is called $array): 如果是这样,这应该为您完成工作(假设您的数组称为$ array):

<table>
    <thead>
        <tr>
            <th>Colour</th>
            <th>Qty</th>
        </tr>
    </thead>
    <tbody>
    <?php foreach($array['qty'] AS $colour => $total) { ?>
        <tr>
            <td><?php echo $colour; ?></td>
            <td><?php echo $total; ?></td>
        </tr>
    <?php } ?>
    </tbody>
</table>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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