0

我有一个大数组。
该数组的内容是:

Array
(
    [0] => Array
        (
            [id] => 12
            [user_id] => 1
            [date] => 2013-10-21 23:01:52
            [type] => 1
            [quantity] => 0
            [value] => 1700
        )

    [1] => Array
        (
            [id] => 13
            [user_id] => 1
            [date] => 2013-10-21 23:01:52
            [type] => 0
            [quantity] => 0
            [value] => 90
        )

    [2] => Array
        (
            [id] => 16
            [user_id] => 1
            [date] => 2013-10-21 23:01:52
            [type] => 0
            [quantity] => 0
            [value] => 0

    [3] => Array
        (
            [id] => 19
            [user_id] => 1
            [date] => 2013-10-31 02:49:12
            [type] => 0
            [quantity] => 0
            [value] => 0
            [bills] => Array
                (
                    [0] => Array
                        (
                            [id] => 5
                            [data_id] => 19
                            [quantity] => 10
                            [value] => 15
                        )

                    [1] => Array
                        (
                            [id] => 5
                            [data_id] => 19
                            [quantity] => 20
                            [value] => 1
                        )

                    [2] => Array
                        (
                            [id] => 5
                            [data_id] => 19
                            [quantity] => 1
                            [value] => 50
                        )

                )

        )

)

我想在 foreach 中显示这个数组。所以我有:

echo '<ol>';
foreach ( $this->data as $d )
{
    echo '<li><strong>'.$d['name'].'</strong><br /></li>';

    if ( $d['bills'] )
    {
        echo '<ul>';
        foreach ( $d['bills'] as $b )
        {
            echo '<li>';
            echo $b['name'];
            echo '</li>';
        }
        echo '</ul>';
    }
}
echo '</ol>';

这很简单,直到我只想显示包含 key['type'] == 1 的数组。我不知道该怎么做。

在 MySQL 中,它只需要添加 'WHERE type = 1'。如果过滤是简单的功能,我了解PHP数组很抱歉。最好的欢呼!

4

2 回答 2

2

如果你真的需要创建一个过滤数组,你可以使用array_filter()回调:

$filtered = array_filter($this->data, function($element) {
    return $element['type'] == 1;
});

否则,最简单的解决方案可能就是将这样的内容放在foreach循环的顶部:

if($d['type'] != 1) {
    continue;
}
于 2013-10-31T21:24:27.063 回答
1

您可以使用一个简单的IF语句 withcontinue来检查是否type等于 1。如果不是,您可以跳过它。

foreach ( $this->data as $d )
{
    if ($d['type'] != 1)  continue;
于 2013-10-31T21:24:40.247 回答