Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an elegant way to reduce an structure to a simple array?

This is a typical array structure:

$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'];

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


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']
    );

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;
 }
like image 708
Peter Krauss Avatar asked Mar 22 '15 22:03

Peter Krauss


1 Answers

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

$names = array_column($strut['resources'][0]['schema']['fields'], 'name');
like image 108
FuzzyTree Avatar answered Oct 01 '22 05:10

FuzzyTree