Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get values of same key from multiple array in php [duplicate]

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
        )

)
like image 264
Arti Singh Avatar asked Mar 16 '26 08:03

Arti Singh


1 Answers

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
)
like image 65
Rahul Avatar answered Mar 18 '26 23:03

Rahul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!