Skip to content
Advertisement

PHP multidimensional array search by value using another value

I need to get the the distinct ‘uid’ and its corresponding ‘name’ , how can I do this in a multidimensional array?

$userdb = array(
array(
    'uid' => '100',
    'name' => 'Sandra Shush',
    'pic_square' => 'urlof100'
),
array(
    'uid' => '5465',
    'name' => 'Stefanie Mcmohn',
    'pic_square' => 'urlof100'
),
array(
    'uid' => '5465',
    'name' => 'Jane Doe',
    'pic_square' => 'urlof100'
),
array(
    'uid' => '40489',
    'name' => 'Michael',
    'pic_square' => 'urlof40489'
), 
array(
    'uid' => '40489',
    'name' => 'Jane Doe',
    'pic_square' => 'urlof40489'
));

sample output:

$data = [{uid: '100', name: 'Sandra Shush'},{uid: '5465', name: ['Stefanie Mcmohn','Jane Doe']}, {uid: '40489', name: ['Michael','Jane Doe']}]

tried working with array_columns and array_keys but i cant think of the right way to get this.

Advertisement

Answer

Try Something like this , here i am storing uid to an array and checking is it already available in the array with in_array function

<?php
$userdb = array(
    array(
        'uid' => '100',
        'name' => 'Sandra Shush',
        'pic_square' => 'urlof100'
    ),
    array(
        'uid' => '5465',
        'name' => 'Stefanie Mcmohn',
        'pic_square' => 'urlof100'
    ),
    array(
        'uid' => '40489',
        'name' => 'Michael',
        'pic_square' => 'urlof40489'
    ),
    array(
        'uid' => '40489',
        'name' => 'Jane Doe',
        'pic_square' => 'urlof40489'
        ));
$newUserDb = array();

$arrayUserId=array();
foreach ($userdb as $user) {
  $newUserDbSingle=array();
  $nameArray=array();
    if (in_array($user['uid'], $arrayUserId))
    {
      $key = array_search ($user['uid'], $arrayUserId);
      $nameArray=$newUserDb[$key]['name'];
      array_push($newUserDb[$key]['name'], $user['name']);
      
    }
    else
    {
      unset($user['pic_square']);
      $arrayUserId[]=$user['uid'];
      $newUserDbSingle=$user;
      $newUserDbSingle['name']=array($user['name']);
      $newUserDb[]=$newUserDbSingle;
    }
}
print_r($newUserDb);
?>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement