Search in array and set value

Asked by At

How can I set value (1, for example) for a key who_use where user_id = 765754346?

And how to get a value of shop_name where user_id = 123456789;

I tried array_filter but haven't any idea how to do this.

array (
  'igive' => 
  array (
    0 => 
    array (
      'name' => 'Alex',
      'shop_name' => 'Shop1',
      'rights' => 'admin',
      'who_use' => '',
      'user_id' => '765754346',
    ),
    1 => 
    array (
      'name' => 'Dmitry',
      'shop_name' => 'Shop2',
      'rights' => 'manager',
      'who_use' => '',
      'user_id' => '123456789',
    ),
  ),
  'giventome' => 
  array (
  ),
)

2 Answers

1
Rakesh Kumar Jakhar On Best Solutions

You can approach this using array_walk

/How can i set value (1, for example) for a key 'who_use' where 'user_id' = 765754346?/

$user_id = '765754346';
array_walk($arr['igive'], function($v, $k) use (&$arr, $user_id){
  ($arr['igive'][$k]['user_id'] == $user_id) ? ($arr['igive'][$k]['who_use'] = 1) : '';
});

Live Demo

/how to get a value of 'shop_nam'e where 'user_id' = 123456789;/

$user_id = '765754346';
$shop_name = '';
array_walk($arr['igive'], function($v, $k) use (&$shop_name, $user_id){
    ($v['user_id'] == $user_id) ? ($shop_name = $v['shop_name']) : '';
}); 
echo $shop_name;

Live Demo

0
Nigel Ren On

If you are going to access the data on a regular basis, it may be better to convert the array so that it is indexed by user_id using array_column() and you can then just directly access each piece of data as you need it...

$baseData = array (
    'igive' =>
    array (
        0 =>
        array (
            'name' => 'Alex',
            'shop_name' => 'Shop1',
            'rights' => 'admin',
            'who_use' => '',
            'user_id' => '765754346',
        ),
        1 =>
        array (
            'name' => 'Dmitry',
            'shop_name' => 'Shop2',
            'rights' => 'manager',
            'who_use' => '',
            'user_id' => '123456789',
        ),
    ),
    'giventome' =>
    array (
    ),
);

$data = array_column($baseData['igive'], null, "user_id");

// For who_use...
echo $data['765754346']['who_use'].PHP_EOL;
// For shop_name...
echo $data['123456789']['shop_name'].PHP_EOL;