2017-10-06 38 views
0

如何使用數組鍵保存陣列中的特定項目。保存具有特定鍵的項目陣列

輸入:

$arr = [ 
    0 => 'item0', 
    2 => 'item2', 
    4 => 'item4', 
    43 => 'item43' 
]; 

現在我只希望保存鍵和。

預期輸出:

$arr = [ 
    2 => 'item2', 
    43 => 'item43' 
]; 

目前代碼:

foreach ($arr as $key => $value) { 
    if(!($key == 2 || $key == 43)) { 
     unset($arr[$key]); 
    } 
} 

它適用於現在,但如果我有更多的數組鍵進行保存。

+1

查看[array_key_exists](http://php.net/manual/en/function.arr ay-key-exists.php) – Epodax

回答

2

你可以試試這個。這裏我們使用array_intersect_keyarray_flip

array_intersect_key使用鍵陣列的交叉點。

array_flip將按鍵和值翻轉數組。

Try this code snippet here

<?php 
ini_set('display_errors', 1); 

$arr = [ 
    0 => 'item0', 
    2 => 'item2', 
    4 => 'item4', 
    43 => 'item43' 
]; 

$keys= [ 
    2, 
    43 
]; 
$result=array_intersect_key($arr, array_flip($keys)); 
print_r($result); 

當前代碼解決方案嘗試here

,您應該使用的||

foreach ($arr as $key => $value) 
{ 
    if($key != 2 && $key != 43) 
    { 
     unset($arr[$key]); 
    } 
} 
print_r($arr); 
+1

這就是我要找的。謝謝 –

+0

@just_a_simple_guy很高興幫助你的朋友...... :) –

1

!=&&,而不是嘗試這種代碼

 <?PHP 
    $mykeys=array(2,5,9,7,3,4); 

    foreach ($arr as $key => $value) { 
     if(!(in_array($key,$mykeys) { 
      unset($arr[$key]); 
     } 
    }?> 
1

你可以把你想保持在一個數組,然後遍歷像這樣的關鍵:

$keys = array(); // put the keys here 
foreach ($arr as $key => $value) { 
    $found = 0; 
    foreach($keys as $filterKey) { 
    if ($key == $filterKey) { 
     $found = 1; 
     break; 
    } 
    $found = 0; 
    } 
    if ($found == 0) { 
    unset($arr[$key]); 
    } 
} 
相關問題