有没有一个优雅的方法来将结构减少到一个简单的数组? [英] Is there an elegant way to reduce an structure to a simple array?

查看:105
本文介绍了有没有一个优雅的方法来将结构减少到一个简单的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是典型的阵列结构

$s = array ('etc'=>'etc', 'fields' => 
  array (
   0 => array (
     'name'=>'year', 'description'=>'Year of ...', 'type'=>'integer',
   ),
   1 =>  array (
     'name'=>'label', 'description'=>'Offical short name', type'=>'string',
   ),
   2 => array (
     'name' => 'xx', 'description' => 'Xx ...', 'type' => 'string',
   )
 ));

这是一个非优雅的方式(或不太优雅的方式)来减少大阵列到一个只包含一列的简单数组:

Here is a non-elegant way (or "not so elegant way") to reduce the big array to a simple array containing just one column:

 $fields = array();
 foreach ($strut['resources'][0]['schema']['fields'] as $r)
    $fields[] = $r['name'];

这是有效的,但是只能使用一个指令吗?可能使用像 array_reduce(),但我看不到如何。

This works, but is it possible to do the same with only one instruction? Perhaps using like array_reduce(), but I not see how.

这里是其他典型的优雅PHP问题:

Here are other typical "elegance PHP problem":

 $fieldsByName = array();
 foreach ($strut['resources'][0]['schema']['fields'] as $r)
    $fields[$r['name']] = array(
        'description' =>$r['description'],
        'type' =>$r['type']
    );

是否有PHP替代?这里的想法是使用关键字(示例中的名称)作为数组键,其他元素作为通常字段,因此,通用非优雅算法是



Is there a PHP alternative? The idea here is to use the keyword (name in the example) as an array key, and the other elements as usual fields, so, the generic non-elegant algorithm is

 $fieldsByName = array();
 foreach ($strut['resources'][0]['schema']['fields'] as $r){
    $key = $r['name'];
    unset($r['name']);
    $fields[$key] = $r;
 }


推荐答案

您可以使用 array_column ,以使用键$ 名称解压所有值另一个数组

You can use array_column to extract all values with key name into another array

$names = array_column($strut['resources'][0]['schema']['fields'], 'name');

这篇关于有没有一个优雅的方法来将结构减少到一个简单的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆