2014-11-23 130 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); 
相關問題