3

I am working in PHP so I have an array like this, from this array I want filter take user_id to another array like I given below.

Array
(
    [0] => Array
        (
            [user_id] => 66
            [distance] => 0
        )

    [1] => Array
        (
            [user_id] => 68
            [distance] => 0
        )

    [2] => Array
        (
            [user_id] => 81
            [distance] => 0
        )

    [3] => Array
        (
            [user_id] => 65
            [distance] => 0.00010218008081861118
        )

)

I want an array like this,

$user_id=array(66,68,81,65);

2 Answers 2

6

Use array_column()

Returns an array of values representing a single column from the input array.

<?php

$user_array = array(
                  0 => array('user_id' => 1, 'name' => 'Bob'),
                  1 => array('user_id' => 2, 'name' => 'John'),
                  2 => array('user_id' => 3, 'name' => 'Mary')
              );

$users = array_column($user_array, 'user_id');

print_r($users);

Output :

Array
(
   [0] => 1
   [1] => 2
   [2] => 3
)
Sign up to request clarification or add additional context in comments.

2 Comments

Learn something new everyday! Didn't even know this function existed.
That's the beauty of programming, always discovering new things. ^_^
5

Where $array is the multidimensional array you provided above:

$data = array();
foreach ($array as $item) {
    $data[] = $item['user_id'];
}
print_r($data);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.