rfc:array_column

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revisionBoth sides next revision
rfc:array_column [2013/01/12 16:45] – Change "0-indexed number" to "integer key" ramseyrfc:array_column [2013/01/12 17:17] – Added Example #4 ramsey
Line 143: Line 143:
     [5342] => Jones     [5342] => Jones
 ) )
 +</code>
 +
 +=== Example #4: Mismatched columns ===
 +
 +With ''array_column()'' the relationship in finding the values of //**columnKey**// to //**indexKey**// is much like that of a SQL left join. All values of the //**columnKey**// are returned. When a corresponding //**indexKey**// cannot be found, the value will be keyed with an integer, starting from zero.
 +
 +The following examples will all use the same **$mismatchedColumns** array defined here:
 +
 +<code php>
 +<?php
 +$mismatchedColumns = array(
 +    array(
 +        'a' => 'foo',
 +        'b' => 'bar',
 +        'e' => 'baz'
 +    ),
 +    array(
 +        'a' => 'qux',
 +        'c' => 'quux',
 +        'd' => 'corge'
 +    ),
 +    array(
 +        'a' => 'grault',
 +        'b' => 'garply',
 +        'e' => 'waldo'
 +    ),
 +);
 +</code>
 +
 +In this example, all rows contain an "a" key, but only two contain a "b" key. If we want to retrieve all "a" values and key them by "b" values, then ''array_column()'' behaves like this:
 +
 +<code php>
 +<?php
 +$foo = array_column($mismatchedColumns, 'a', 'b');
 +$bar = array('bar' => 'foo', 'qux', 'garply' => 'grault');
 +
 +/*
 +Both $foo and $bar contain values that look like this:
 +
 +Array
 +(
 +    [bar] => foo
 +    [0] => qux
 +    [garply] => grault
 +)
 +*/
 +</code>
 +
 +However, if we want to retrieve all "b" values and key them by "a" values, we will only have two elements in the resulting array, since only two rows contain "b" values.
 +
 +<code php>
 +// There is a corresponding "a" value for each "b" value
 +print_r(array_column($mismatchedColumns, 'b', 'a'));
 +
 +/*
 +Array
 +(
 +    [foo] => bar
 +    [grault] => garply
 +)
 +*/
 +
 +// There are no corresponding "c" values for either "b" value
 +print_r(array_column($mismatchedColumns, 'b', 'c'));
 +
 +/*
 +Array
 +(
 +    [0] => bar
 +    [1] => garply
 +)
 +*/
 </code> </code>
  
rfc/array_column.txt · Last modified: 2017/09/22 13:28 by 127.0.0.1