2

我有以下数组:

$var_array = array(
 "length"  => 5,
 "breadth"  => 5,
 "color" => "blue",
 "size"  => "medium",
 "shape" => "square");

如何通过指定键从数组中提取选定的变量?

例如,如果我指定breadthand size,我会得到:

$breadth = 5;
$size = "medium";
$var_array = array(
 "length"  => 5,
 "color" => "blue",
 "shape" => "square");
4

4 回答 4

1

解决方案:

$keys = array('breadth', 'size');  // which keys do you want to extract?

foreach($keys as $key) {
    $newArr[$key] = $var_array[$key];  // put'em in newArr
    unset($var_array[$key]);
}
extract($newArr);   // extract them to convert keys to variables
unset($newArr);   // unset newArr
于 2012-08-17T12:16:51.277 回答
1

array_diff_keyarray_intersect_key

$array  = array(
  'breadth' => 1, 
  'size' => 2, 
  'length' => 3,
  'colour' => 4,
  'shape' => 5
);

$keys      = array('breadth', 'size');
$new_array = array_intersect_key($array, array_flip($keys));
$array     = array_diff_key($array, $new_array);

将产生:

// $new_array
array(2) {
 ["breadth"] => int(1)
 ["size"]    => int(2)
}

// $array
array(3) {
 ["length"] => int(3)
 ["colour"] => int(4)
 ["shape"]  => int(5)
}

如果要将它们放入局部变量中,可以执行以下操作:

list($length, $colour, $shape) = array_values($new_array);

或者一个不太清楚的版本:

extract($new_array);
于 2012-08-17T12:27:00.820 回答
0

Goldenparrot 已经提供了一个很好的答案,但是如果您想要一个不使用 foreach 的解决方案,您可以使用array_intersect_key代替:

$var_array = array(...)
$keysToExtract = array('breadth', 'size');
extract(array_intersect_key($var_array, array_fill_keys($keysToExtract, true));
于 2012-08-17T12:16:57.593 回答
0

试试这个

$var_array = array(
 "length"  => 5,
 "breadth"  => 5,
 "color" => "blue",
 "size"  => "medium",
 "shape" => "square");


reset($var_array);
$myarray =array();


while (list($key, $val) = each($var_array))
{
  if($key!='length' && $key!='size' )
  {
    $myarray[$key] =  $val;

  }else{

   echo "$key => $val<br />";

 }


}

输出

size=> medium
breadth => 5

Array
(
    [color] => blue
    [length] => 5
    [shape] => square
)
于 2012-08-17T12:25:48.053 回答