php和laravel数组指定元素作为键和值

2021-02-04 04:16

阅读:812

标签:组元   val   column   数据   wan   lis   php   cti   col   

php和laravel数组指定元素作为键和值

//测试数据
$data = [
    [‘sn‘ => ‘sn001‘, ‘name‘ => ‘zhangsan‘, ‘age‘ => ‘24‘],
    [‘sn‘ => ‘sn002‘, ‘name‘ => ‘lisi‘, ‘age‘ => ‘25‘],
    [‘sn‘ => ‘sn003‘, ‘name‘ => ‘wangwu‘, ‘age‘ => ‘26‘],
];

php实现

//指定元素作为键
$key = array_column($data, ‘sn‘);
$keyBy = array_combine($key, $data);

//指定元素作为键和值(比如:指定sn为键,name为值)
$key = array_column($data, ‘sn‘);
$value = array_column($data, ‘name‘);
$pluck = array_combine($key, $value);

laravel实现

//指定数组元素作为键名
$collection = collect($data);
$keyBy = $collection->keyBy(‘sn‘);

//指定元素作为键和值(比如:指定sn为键,name为值)
$pluck = $collection->pluck(‘name‘, ‘sn‘);

php和laravel数组指定元素作为键和值

标签:组元   val   column   数据   wan   lis   php   cti   col   

原文地址:https://www.cnblogs.com/trblog/p/12797583.html


评论


亲,登录后才可以留言!