像perl中的哈希切片一样的数组切片

时间:2018-08-07 06:26:46

标签: php

是否有内置功能,或更短的方法将元素提取到新数组中,如此处所述?

<?php

function arr_slice ($arr, $keys) {
  $ret = array();
  foreach ($keys as $k) { $ret[$k] = $arr[$k]; }

  return $ret;
}

$array = array(
  "a" => 1,
  "b" => 2,
  "c" => 3,
  "d" => 4,
);
var_export(
  arr_slice($array, array("x","d","b"))
);

输出(关键顺序很重要)

array (
  'x' => NULL,
  'd' => 4,
  'b' => 2,
)

0 个答案:

没有答案