查找特定值数组多维php

时间:2014-10-16 20:21:46

标签: php arrays multidimensional-array

我是关于PHP的新手,我希望找到0,并在多维数组中替换内部数组内遗漏的数字。如果内部数组有两个以上的0,则会被忽略并转到下一个。

$list = array("First"=>array(0,1,2,3,0,5,6,7,8,9), 
                "Second"=>array(0,1,2,3,4,5,6,7,8,9), 
                "Third"=>array(0,1,2,3,4,5,0,0,8,9), 
                "Fourth"=>array(0,1,2,3,4,5,6,7,8,0),
                "Fifth"=>array(0,1,2,3,4,5,0,7,8,9),
                "Sixth"=>array(0,0,0,3,4,5,6,0,0,0),
                "Seventh"=>array(0,1,2,3,0,0,6,7,8,9),
                "Eighth"=>array(0,1,2,3,4,5,0,7,8,9),
                "Ninth"=>array(0,1,2,3,4,0,6,7,8,9),
                "Tenth"=>array(0,0,2,3,4,5,6,7,8,9));

$countZero = 0;
    foreach($list as $lvl) {
    foreach($lvl as $ind => $val) {
       if($countZero = array_count_values($lvl[$val] === 0))
        $list[$ind][$val] = 45 - array_sum($ind);

        echo $count;
    }
}

我希望所有内部数组,只有两个0只得到一个,以便按顺序排列所有数字,即

"First"=>array(0,1,2,3,4,5,6,7,8,9);

请帮助我。

我在下面尝试了这段代码,试图找到0。

$counts = 0;
$newArr = array();
    foreach($list as $lvl) {

        if(is_array($lvl)) {
            for($i = 0; $i < count($lvl) - 1;  $i++) {
                  if(($lvl[$i] == 0) < 2){
                    $counts++;
                    $newArr[$i] = 45 - array_sum($lvl);
                 }

                }

            }
        } 
        print_r($newArr);

2 个答案:

答案 0 :(得分:0)

事实上,这就是我所做的和工作。

    $list = array(array(1,2,3,0,5,6,7,8,9),
                   array(1,2,3,4,5,6,7,8,9),
                   array(1,2,3,4,5,0,0,8,9),
                   array(1,2,3,4,5,6,7,8,0),
                   array(1,2,3,4,5,0,7,8,9),
                   array(0,0,3,4,5,6,0,0,0),
                   array(1,2,3,0,0,6,7,8,9),
                   array(1,2,3,4,5,0,7,8,9),
                   array(1,2,3,4,0,6,7,8,9));


        for($l = 0; $l < count($list); $l++) 
        {
            $total = 0;
            $countZ = 0;
            for($i=0; $i < 9; $i++)
            {
     if($list[$l][$i] == 0)
                {
                    $countZ++;
                    $indexZero = $i;
                }
                $total += $list[$l][$i];
                if($countZ > 1) {
                    break;
                }
            }
            $list[$l][$indexZero] = 45 - $total;
        }
     print_r($list);    

TY all。

答案 1 :(得分:0)

这是使用array_walk的解决方案:

array_walk($list,
           function(&$numbers) {
               $zeroIndex = 0;
               foreach($numbers as $i => $number) {
                   if( $number === 0 ) {
                       if( $zeroIndex > 0 ) {
                           return;
                       }
                       $zeroIndex = $i;
                   }
               }
               $numbers[$zeroIndex] = $zeroIndex;
           });
  • 您不需要计算所有零。您只需要检查是否少于3个零。
  • 我将索引(位置)保存为零($zeroIndex = $i)。
  • 我假设第一个数字始终为零($zeroIndex = 0)。
  • 第二个零的索引大于零。如果我在最后找到的零的索引大于零(if( $zeroIndex > 0 ))时找到零,则表示有两个以上的零。