我有类似的数组
$data = [
'phone' => '9999999999',
'body' => 'Sample Message',
'caption' => 'Sample',
'filename' => 'Sample File.PDF'
];
我想将数组中的特定部分放入另一个数组中,例如
$t_data = [
'phone' => '9999999999',
'body' => 'Sample Message'
];
该怎么做? 而且应该是单行功能
答案 0 :(得分:1)
您可以使用laravel帮助器array_only():
$t_data = array_only($data, ["phone", "body"]);
答案 1 :(得分:0)
如果您要分割一个数组,可以这样做:
array_slice($data, 0, 2);
它将从零位置开始获取前两个值。
答案 2 :(得分:0)
尝试
$t_data = [
'phone' =>$data['phone'],
'body'=>$data['body']
];
答案 3 :(得分:-1)
赞
print_r(array_intersect_key($data, ['phone'=>0,'body'=>0]));
输出
Array
(
[phone] => 9999999999
[body] => Sample Message
)
或作为功能
function getArrayItems(array $array,$items,$separator=','){
if(!is_array($items)) $items = array_filter(array_map('trim',explode($separator,$items)),function($i){
return strlen($i);
});
return array_intersect_key($array, array_flip($items));
}
$data = [
'phone' => '9999999999',
'body' => 'Sample Message',
'caption' => 'Sample',
'filename' => 'Sample File.PDF'
];
print_r(getArrayItems($data, 'body')); // returns [body=>'Sample Message']
print_r(getArrayItems($data, ['body'])); // returns [body=>'Sample Message']
print_r(getArrayItems($data, ['body','caption'])); // returns [body=>'Sample Message','caption' => 'Sample']
print_r(getArrayItems($data, 'body,caption')); // returns [body=>'Sample Message','caption'=>'Sample']
print_r(getArrayItems($data, ' body , caption ')); // returns [body=>'Sample Message','caption'=>'Sample']
print_r(getArrayItems($data, 'body|caption','|')); // returns [body=>'Sample Message','caption'=>'Sample']