0

假设我们有数组:

$array1 = array (
    'key1' => 1,
    'non1' => 1,
    'key2' => 1,
    'non2' => 1,
    'non3' => 1,
    'non4' => 1,
    'key3' => 1,
    'key4' => 1
);

如何移动所有具有key nameLIKE的键"key"并将它们移动到另一个数组。

$array2 = movekey('key',$array1);

会给:

array1 = array (
    'non1' => 1,
    'non2' => 1,
    'non3' => 1,
    'non4' => 1

);

array2 = array (
    'key1' => 1,
    'key2' => 1,
    'key3' => 1,
    'key4' => 1
);
4

4 回答 4

3
$array2 = array();
   foreach($array1 as $key => $val) {
     if(strpos($key,'key')!==false){
        $array2[$key] = $val; //Copy all the values that have key-name like 'key'.
        unset($array1[$key]); //Removes the copied key and value.
     }
   }
于 2013-04-06T06:48:58.270 回答
2
$result = array();
foreach ($array as $key => $value) {
  if (strpos($key, 'key') !== false) {
    $result[$key] = $value;
  }
}
于 2013-04-06T06:41:05.887 回答
2

只是因为它看起来很有趣,所以按照 OP 的原始愿望把它放在函数形式中:

function moveKey($cmp, Array & $ar)
{
    $y = array();
    foreach($ar as $key => $value) {
        if(strpos($key, $cmp) !== false) {
            $y[$key] = $value;
            unset($ar[$key]);
        }
    }
    return $y;
}

然后测试功能:

$array1 = array (
    'key1' => 1,
    'non1' => 1,
    'key2' => 1,
    'non2' => 1,
    'non3' => 1,
    'non4' => 1,
    'key3' => 1,
    'key4' => 1
);

$a2 = moveKey('key', $array1);
echo "<pre>". print_r($array1, true) ."\n". print_r($a2, true) ."</pre>";

它输出:

Array
(
    [non1] => 1
    [non2] => 1
    [non3] => 1
    [non4] => 1
)

Array
(
    [key1] => 1
    [key2] => 1
    [key3] => 1
    [key4] => 1
)

玩得开心!

于 2013-04-06T07:00:28.287 回答
1
foreach (array_keys($array1) as $key) {
    if (!preg_match('/^key\d+/', $key)) {
        unset($array1[$key]);
    }
}
print_r ($array1);   
于 2013-04-06T07:06:45.773 回答