搜索数组并设置值

时间:2019-05-10 15:11:23

标签: php arrays

如何为who_use = 765754346的键user_id设置值(例如1)?

以及如何获取值shop_name,其中user_id = 123456789;

我尝试了array_filter,但不知道如何执行。

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 个答案:

答案 0 :(得分:1)

您可以使用array_walk

/ 如何为其中“ user_id” = 765754346的键“ who_use”设置值(例如1)? /

$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

/ 如何获取'shop_nam'e的值,其中'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

答案 1 :(得分:0)

如果要定期访问数据,则最好转换数组,以便使用user_idarray_column()对其进行索引,然后可以直接访问每个数据块您需要的数据...

$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;