从php中的多个数组中获取相同键的值

时间:2017-04-13 11:59:26

标签: php arrays multidimensional-array key

我试图分开" TID"在这些多个阵列的数组中,但我无法找到有效的解决方案。

我在一个变量中使用了以下类型的数组:

Array
(
    [0] => Array
        (
            [tid] => 168
        )

)
Array
(
    [0] => Array
        (
            [target_id] => 14
        )

    [1] => Array
        (
            [target_id] => 15
        )

    [2] => Array
        (
            [target_id] => 37
        )

)
Array
(
)
Array
(
    [0] => Array
        (
            [target_id] => 36
        )

)
Array
(
    [0] => Array
        (
            [target_id] => 14
        )

    [1] => Array
        (
            [target_id] => 15
        )

)
Array
(
    [0] => Array
        (
            [target_id] => 36
        )

)
Array
(
    [0] => Array
        (
            [tid] => 168
        )

    [1] => Array
        (
            [tid] => 167
        )

)

这些值在一个变量中,可以有无限的数组。

预期产出:

Array
(
    [0] => Array
        (
            [tid] => 168
        )
    [1] => Array
        (
            [tid] => 168
        )

    [2] => Array
        (
            [tid] => 167
        )

)

2 个答案:

答案 0 :(得分:3)

您正在搜索array_column

这是语法

array array_column ( array $input , mixed $column_key [, mixed $index_key = null ] )

描述

array_column — Return the values from a single column in the input array

示例:

$records = array(
    array(
       tid => 167
    ),
    array(
        'id' => 3245,
        'first_name' => 'Sally',
         tid => 166
    ),
    array(
        'id' => 5342,
        'first_name' => 'Jane',
         tid => 168
    ),
    array(
        'id' => 5623,
        'first_name' => 'Peter',
         tid => 169
    )
);

$ids= array_column($records, 'tid');

输出:

Array
(
    [0] => 167
    [1] => 166
    [2] => 168
    [3] => 169
)

如果您有更多阵列,

$records1 = [ ['tid' => 169]];
$ids1 = array_column($records1, 'tid');

然后你可以做array_merge

$ids = array_merge($ids, $ids1);

输出:

Array
(
    [0] => 167
    [1] => 166
    [2] => 168
    [3] => 169
    [4] => 169
)

答案 1 :(得分:1)

$arr1= array("1"); // first 
$arr2 = array("2") // second array
$new = array();

foreach($arr1 as $key=>$value){
 if($key=="yourkey"){
   $new[]=$value;
 }
}

foreach($arr2 as $ke2=>$valu2){
   if($key2=="yourkey"){
     $new[]=$value2;
   }
 }

 print_r($new);