在PHP中过滤数组的数据并添加一个字段

时间:2015-07-28 21:05:31

标签: php arrays foreach

我有以下数组:

Array
(
    [data] => Array
        (
            [0] => Array
                (
                    [amount] => 16800
                    [created] => 1438114651
                    [status] => pending
                )

            [1] => Array
                (
                    [amount] => 16800
                    [created] => 1435854159
                    [status] => available
                )

            [2] => Array
                (
                    [amount] => 3300
                    [created] => 1435711645
                    [status] => available
                )
        )
)

我只需要使用sum of the amounts以及两个创建日期之间的available status过滤此数组吗?

我需要foreach吗?

非常感谢你的帮助。

2 个答案:

答案 0 :(得分:2)

你可能正在寻找这样的东西:

main

我使用function totalAmount($array, $start = 0, $end = 1E+11) { $totalAvailable = 0; foreach($array as $item) { if( $item['status'] == 'available' && $item['created'] >= $start && $item['created'] < $end ) $totalAvailable += $item['amount']; } return $totalAvailable } $sum = totalAmount($foo['data'], $unixtimeStart, $unixtimeEnd); 作为开始条件,但您可以根据需要进行调整。 此外,start和end参数现在是可选的。

答案 1 :(得分:1)

请试试这个

$data=    Array
(
    [data] => Array
        (
            [0] => Array
                (
                    [amount] => 16800
                    [created] => 1438114651
                    [status] => pending
                )

            [1] => Array
                (
                    [amount] => 16800
                    [created] => 1435854159
                    [status] => available
                )

            [2] => Array
                (
                    [amount] => 3300
                    [created] => 1435711645
                    [status] => available
                )
        )
)

$createdFrom = ...; // from date
$createdTo=...; // to date
$total=0;
foreach($data['data'] as $array)
    if($array['created'] > $createdfrom && $array['created'] < $createdTo) 
        if($array['status']=="available")
            $total+=$array['amount'];
echo $total;