2013-03-13 101 views
0

如何計算數組的部分?例如:切片數組和計數

陣:

[name] => Michael 
[surname] => Hadfield 
[midname] => Olsow 
[email] => [email protected] 
[phone] => 3342020 

我想算陣列領域排除[midname]和[電話] 所以結果應該是3

同時,我想從這個創建數組陣列結果:

[name] => Michael 
[surname] => Hadfield 
[email] => [email protected] 

這可能嗎?

+0

[你有什麼嘗試?](http://www.whathaveyoutried.com/)請參見[ask advice](http://stackoverflow.com/questions/ask-advice)。 – 2013-03-13 01:20:50

回答

1

你可以嘗試這樣的事情:

$keys_to_exclude = array('midname', 'phone'); 
$new_array = array_diff_key($original_array, array_flip($keys_to_exclude)); 
echo count($new_array); 
print_r($new_array); 

有了這個輸入數組:

$original_array = array( 
    'name' => 'Michael', 
    'surname' => 'Hadfield', 
    'midname' => 'Olsow', 
    'email' => '[email protected]', 
    'phone' => 3342020 
); 

你應該得到your desired output,也就是echo count();打印3所得$new_array是:

Array 
(
    [name] => Michael 
    [surname] => Hadfield 
    [email] => [email protected] 
) 
+0

它給了我一個錯誤: 警告(2):array_combine()[function.array-combine]:兩個參數應該有相同數量的元素[APP/Controller/UsersController.php,98行] Warning ):array_diff_key()[function.array-diff-key]:參數#2不是數組[APP/Controller/UsersController.php,第99行] /app/Controller/UsersController.php(line 100) null – 2013-03-13 01:44:58

0
  1. 使用循環計數的部分你想

  2. 乘以·6(假設總有五個部分和三個要算)

    $count = count($array) * .6;的的count($array)結果

+0

但在這種情況下,它也會計算該字段。我需要排除它們。 – 2013-03-13 01:23:23

0

我猜你總是可以在陣列,取消設置2個索引複製,再算上它:

$array_copy = $array; 
unset($array_copy('midname')); // Note unsetting a non-existent key does NOT throw an error. 
unset($array_copy('phone')); 
echo count($array_copy);