Get values of same key from multiple array in php

2019-07-30 15:27发布

I'm trying to separate the "TID" in an array from these multiple arrays but I couldn't find the efficient solution.

I've the following type of arrays in one variable:

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
        )

)

These values are in one variable and there can be unlimited arrays.

And Expected Output:

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

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

)

2条回答
老娘就宠你
2楼-- · 2019-07-30 15:38

You are searching for array_column.

Here is the syntax

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

Description

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

Example :

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

OUTPUT :

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

If you have more arrays,

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

then you can do array_merge.

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

OUTPUT :

Array
(
    [0] => 167
    [1] => 166
    [2] => 168
    [3] => 169
    [4] => 169
)
查看更多
Luminary・发光体
3楼-- · 2019-07-30 15:50
$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);
查看更多
登录 后发表回答