【问题标题】:Repeating value into an array after a merge in php在php中合并后将值重复到数组中
【发布时间】:2013-05-05 14:11:09
【问题描述】:

不明白为什么在我的最终结果中 Shifts-5 一次又一次地重复,而在我的数组中他只在这里一次...

感谢您的帮助。

http://codepad.org/XoBmnHFr

<?php

$firstArray = array("Leaves-19", "Shifts-5", "Shifts-1", "Shifts-1", "Shifts-1", "Shifts-1", "Leaves-19", "Leaves-19", "Shifts-1", "Shifts-1", "Shifts-1", "Shifts-1", "Shifts-1", "Leaves-19", "Leaves-19", "Shifts-1", "Shifts-1", "Shifts-1", "Shifts-1", "Shifts-1", "Leaves-19", "Leaves-19", "Shifts-1", "Shifts-1", "Shifts-1", "Shifts-1", "Shifts-1", "Leaves-19", "Leaves-19", "Shifts-1", "Shifts-1", "Shifts-1", "Shifts-1", "Shifts-1", "Leaves-19", "Leaves-19", "Shifts-1", "Shifts-1", "Shifts-1", "Shifts-1", "Shifts-1", "Leaves-19");

$secondArray = array("2013-04-28", "2013-04-29", "2013-04-30", "2013-05-01", "2013-05-02", "2013-05-03", "2013-05-04");

$thirdArray = array("13", "10", "12", "9", "14", "11");


$datesCount        = count( $secondArray );
$firstArrayLength  = count( $firstArray );
$thirdArrayLength  = count( $thirdArray );

for( $i=0 ; $i < $thirdArrayLength ; $i++ )
{
    $currentThirdArrayValue = $thirdArray[$i];

    for( $inner=0, $firstArrayIndex=0 ; $inner < $datesCount ; $inner++, $firstArrayIndex++ )
    {
        if( $firstArrayIndex == $firstArrayLength )
                $firstArrayIndex = 0;

        echo "{$secondArray[$inner]} / {$currentThirdArrayValue} / {$firstArray[$firstArrayIndex]}<br/>\n";
    }
}

?>

【问题讨论】:

  • 你到底想用你的代码做什么?我想知道,所以我了解您的问题/问题。
  • 因为您在执行$firstArrayIndex = 0; 时一次又一次地迭代$firstarray ..
  • 你能给出预期输出的想法吗......
  • 好的。第一个数组,如果用户需要在当天制作(例如 Shifts-41 是从上午 9 点到下午 5 点)。第二个数组是要知道当前视图/表中的日期。第三个是给用户的。我知道一周有7天。我的第一个数组有 42 个数据。 42/7=6。我有 6 个用户。我想要每个日期,每个用户,他需要做的每种类型的日子。有了它的解决方案 Elvena 非常接近,但如果用户的日期类型不同,则会出现问题。
  • 对于预期结果,请参阅我的评论:codepad.org/XoBmnHFr#comment-LidycMfX 谢谢。

标签: php arrays


【解决方案1】:

可以在没有所有计数器的情况下完成,如下所示:

$secondArray = array("2013-04-28", "2013-04-29", "2013-04-30", "2013-05-01", "2013-05-02", "2013-05-03", "2013-05-04");

$thirdArray = array("13", "10", "12", "9", "14", "11");

$secondArrayLength = count($secondArray);

foreach($thirdArray as $third_i => $third_value)
{
    foreach($secondArray as $sec_i => $sec_value)
    {
        $first_value = $firstArray[($third_i * $secondArrayLength) + $sec_i];
        echo "$sec_value / $third_value / $first_value<br/>" ;
    }
}

【讨论】:

    【解决方案2】:

    这是因为您在第三个数组的每次迭代中都不断重置第一个数组内的指针:

    $firstArrayIndex=0;
    

    将此分配移到外部for 循环之外。

    Demo

    【讨论】:

    • @kdazzle 好吧,php 中没有指针,所以请发挥你的想象力吧 :)
    猜你喜欢
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2015-06-04
    • 2017-12-13
    • 2021-06-19
    • 2020-06-23
    • 2018-10-14
    • 1970-01-01
    相关资源
    最近更新 更多