0

I have a question. Suppose I have an array like this :

Array
(
   [0] => Array
       (
          [id] => 4
          [name] => test
          [surname] => test1
       )
   [1] => Array
       (
           [id] => 6
           [name] => test4
           [surname] => test5
       )
)

I need to get all data for array by id. So for example if I want to get data for id=4 I need to get an array like this :

Array
 (
    [id] => 4
    [name] => test
    [surname] => test1
 )

I tried with array_column but not work. Please help me

Pavel Petrov
  • 847
  • 10
  • 19
Harea Costicla
  • 797
  • 3
  • 9
  • 20
  • 6
    *I tried with array_column* Show that code. You are probably closer to the solution than you think. – Rizier123 May 11 '16 at 08:03
  • Right, You are near to your destination. – Murad Hasan May 11 '16 at 08:05
  • @HareaCosticla, Your answer is ready at [Answer](http://stackoverflow.com/questions/37156500/get-an-array-from-multidimensional-by-a-value/37156674#37156620) – Murad Hasan May 11 '16 at 08:12
  • Here you have some answers on how to search the id, then you can get the rest... http://stackoverflow.com/questions/6661530/php-multi-dimensional-array-search/24527099#24527099 – angoru May 11 '16 at 08:22

2 Answers2

0

With help of array_combine() & array_column()

$array = array
(
   '0' => array
       (
          'id' => 4,
          'name' => 'test',
          'surname' => 'test1',
       ),
   '1' => array
       (
           'id' => 6,
           'name' => 'test4',
           'surname' => 'test5',
       )
);    
// Create array as id as index
$temp = array_combine(array_column($array, 'id'), $array);
// get the sub array
$new = $temp[4];
var_dump($new);

Another simple way would be -

$new = array();

foreach($array as &$v) {
    if($v['id'] == 4) {
        $new = $v;
        break;
    }
}

var_dump($new);

Output

array(3) {
  ["id"]=>
  int(4)
  ["name"]=>
  string(4) "test"
  ["surname"]=>
  string(5) "test1"
}
Sougata Bose
  • 31,517
  • 8
  • 49
  • 87
0

You should need to have a loop and checking if the id of the sub array is your searching id or not, if it is then store then sub array and break.

$arr = array(
           array('id' => 4, 'name' => 'test', 'surname' => 'test1'),
           array('id' => 6, 'name' => 'test4', 'surname' => 'test5')
        );

$id = 4;
$out = array();
foreach($arr as $val){
    if($val['id'] == $id){
        $out = $val;
        break;
    }

}
echo '<pre>';
print_r($out);

Check this out: Online check

Murad Hasan
  • 9,565
  • 2
  • 21
  • 42