2014-11-23 132 views
0

我有一个数组,其中包含一些不同点的数值。我想检查索引中是否有值,然后把它放在一个从0开始的新数组中,然后放入索引1,然后将下一个值放入索引2,依此类推。我需要缩短它并将它们全部移到左边。如何检查一个数组索引是否包含一个值

Array ([0] => 53 [1] => [2] => 55 [3] => 76 [4] => [5] => [6] => [7] =>) 

新的阵列将是:

newArray ([0] => 53 [1] =>55 [2] => 76) 

也许是这样的:

for ($i=0; $i < sizeof($questionWorth); $i++) 
{ 
    if($questionWorth[$i] has a value) 
    { 
     put it in new array starting at index zero 
     then increment the index of new array 
    } 
} 
+3

你“也许是这样的”解决方案是好的另一个柜台。 – zerkms 2014-11-23 22:30:01

+0

但我不没有如何在PHP中实现该解决方案... – 2014-11-23 22:30:39

+0

'if($ questionWorth [$ i]!='')$ newArray [] = $ questionWorth [$ i];' – 2014-11-23 22:31:28

回答

2

只得到价值不是NULL或清空你可以使用array_filter()array_values()这样的:

$array = array(76, NULL, NULL, 56); 
// remove empty values from array, notice that since no callback 
// is supplied values that evaluates to false will be removed 
$array = array_filter($array); 
// since array_filter will preserve the array keys 
// you can use array_values() to reindex the array numerically 
$array = array_values($array); 
// prints Array ([0] => 76 [1] => 56) 
print_r($array); 
+1

非常感谢你! – 2014-11-23 22:49:47

+0

@DinoBicBoi - 很高兴我可以帮助=) – Cyclonecode 2014-11-23 22:50:35

+0

它不会这样工作,但它使([0] => 76,[3] => 56)而不是0和一个 – 2014-11-23 22:57:44

0

您可以使用

  array_filter($yourArray) 

它会删除所有空值你

+0

不,它会删除所有的空值与他们的钥匙 – Milad 2014-11-23 22:33:30

0

尝试array_filter这使得正是这种

var_dump(array_filter(array(0 => 55, 1 => 60, 2 => null))) 
0

如果你想检查是否索引有一个值,这样做:

$variable = array ([0] => 53, [1] => , [2] => 55, [3] => 76, [4] => , [5] => , [6] => , [7] =>) 

foreach ($variable as $key => $value) { 
     var_dump($key.' => '.$value); 
    } 
0

这很简单: if ($array [$i]),然后把值在另一个数组与从0开始

$array = array(76, NULL, NULL, 56); 
$count = 0; 

for ($i=0; $i < sizeof($array); $i++) 
{ 
    if($array[$i]) 
    { 
     $arr[$count] = $array[$i]; 
     $count++; 
    } 
}; 

print_r($array); 
print_r($arr); 
相关问题