数组推送不起作用? PHP

时间:2017-01-22 14:21:35

标签: php arrays array-push

我正在尝试将5个日期($completion_date)放入数组中我有一个列表我正在循环将$completion_date传递给下面的函数,有多个相同的实例{{ 1}}在列表中,但我只想要数组$completion_date中的每一个,所以每次使用$completion_dates = [];搜索数组时如果当前array_search($completion_date, $completion_dates);不存在,我想要将它添加到数组中,如果是,我想在各自数组中的相同位置修改$completion_date$completions。我的问题是array_push似乎没有推出所有日期?只有一个?

我已经检查了array_push所在的if语句,并且每次都在运行else子句(因为array_push不能改变它);

$payouts

输出:function sortResults($completion_date, $payout){ global $completion_dates, $completions, $payouts; $completion_dates = []; $completions = [0,0,0,0,0]; // not in use $payouts = [0,0,0,0,0]; // not in use // check is $completion_date is in $completion_dates array and get position if so. $position = array_search($completion_date, $completion_dates); if ($position) { // update $payouts and $completions @ same $position. }else{ // add $completion_date to $completion_dates array. array_push($completion_dates, $completion_date); } } var_dump($completion_dates);

但是还应输出其他四个日期array(1) { [0]=> string(10) "22/01/2017" }"18/01/2017""19/01/2017""20/01/2017"“?

我正在循环的数据正在逃避日期,因此"21/01/2017不确定它是否重要,它真的不应该?

1 个答案:

答案 0 :(得分:1)

因为您每次都会在函数中覆盖$ completion_dates。

function sortResults($completion_date, $payout)
{
    global $completion_dates, $completions, $payouts;

    $completion_dates = []; <----------------------- HERE
    $completions = [0, 0, 0, 0, 0]; // not in use
    $payouts = [0, 0, 0, 0, 0]; // not in use


    // check is $completion_date is in $completion_dates array and get position if so.
    $position = array_search($completion_date, $completion_dates);

    if ($position) {
        // update $payouts and $completions @ same $position.
    } else {
        // add $completion_date to $completion_dates array.
        array_push($completion_dates, $completion_date);
    }

}