开发者

Reducing multidimensional array

I have the following multidimensional array:

Array
(
    [0] => Array
        (
            [area] => 5
            [estante] => 5
            [anaquel] => 5
            [no_caja] => 5
            [id_tipo] => 3
            [nombre_tipo] => Administrativo
        )
[1] =&开发者_C百科gt; Array
    (
        [area] => 5
        [estante] => 5
        [anaquel] => 5
        [no_caja] => 5
        [id_tipo] => 1
        [nombre_tipo] => Copiador
    )

[2] => Array
    (
        [area] => 5
        [estante] => 5
        [anaquel] => 5
        [no_caja] => 5
        [id_tipo] => 2
        [nombre_tipo] => Judicial
     )

)

and I want to reduce it by having all the different values (intersection) between them. The dimension of the array may change (I'm retrieving the info from a database). I have thought in using functions like array_reduce and array_intersect, but I have the problem that they work only with one-dimension arrays and I can't find the way to pass an indefinite (not previous known) number of parameters to these function. I'd like to have an output like this:

Array([0]=>Copiador, [1]=>Administrativo, [2]=>Judicial).

How can I do this?

Thanks in advance.


$arr=array(
  array (
    'area' => 5 ,
    'estante' => 5 ,
    'anaquel' => 5,
    'no_caja' => 5,
    'id_tipo' => 3,
    'nombre_tipo' => 'Administrativo'),
  array (//etc.
  )
); 

$fn=function(array $a, $k){
    if(array_key_exists($k,$a)) return $a[$k];
};

$b=array_map($fn,$arr,array_fill(0,count($arr),'nombre_tipo'));
print_r($b);

/*
Array
(
    [0] => Administrativo
    [1] => Copiador
    [2] => Judicial
)
*/


$reduced = array();
foreach ($oldarray as $value) {
    $reduced[] = $value['nombre_tipo'];
}

Although, a better solution may be to just modify your SQL query so you get the correct data to begin with.

Note: you can also do it with array_reduce, but I personally prefer the method above.

$reduced = array_reduce($oldarray,
                        function($a, $b) { $a[] = $b['nombre_tipo']; return $a; },
                        array()
                       );


This task is exactly what array_column() is for -- extracting columnar data.

Call this:

var_export(array_column($your_array, 'nombre_tipo'));

This will output your desired three-element array. ...I don't understand the sorting in your desired output.


Seems like you want array_map


$newArr = array_map(function($a) {
    return $a['nombre_tipo'];
}, $oldArr);

var_dump($newArr);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜