PHP多维数组按值搜索

新手上路,请多包涵

我有一个数组,我想在其中搜索 uid 并获取数组的键。

例子

假设我们有以下二维数组:

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

函数调用 search_by_uid(100) (第一个用户的 uid)应该返回 0

函数调用 search_by_uid(40489) 应该返回 2

我尝试制作循环,但我想要更快的执行代码。

原文由 Rachit 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 528
2 个回答
function searchForId($id, $array) {
   foreach ($array as $key => $val) {
       if ($val['uid'] === $id) {
           return $key;
       }
   }
   return null;
}

这将起作用。你应该这样称呼它:

 $id = searchForId('100', $userdb);

重要的是要知道,如果您使用 === 运算符比较类型必须完全相同,在此示例中,您必须搜索 string 或只使用 == 而是 ===

基于 angoru的 回答。在更高版本的 PHP ( >= 5.5.0 ) 中,您可以使用单线。

 $key = array_search('100', array_column($userdb, 'uid'));

这是文档:http: //php.net/manual/en/function.array-column.php

原文由 Jakub Truneček 发布,翻译遵循 CC BY-SA 4.0 许可协议

我一直在寻找类似于 MySQL LIKE %term% 的功能。基于此页面上的答案。我能够从文件中搜索 JSON 数组。

user_list.json 如下所示:

 {
  "user-23456": {
        "name": "John Doe",
        "age": "20",
        "email": "doe@sample.com",
        "user_id": "23456"
    },
    "user-09876": {
        "name": "Ronojoy Adams",
        "age": "35",
        "email": "joy@sample.com",
        "user_id": "09876"
    },
    "user-34890": {
        "name": "Will Artkin",
        "age": "16",
        "email": "will@sample.com",
        "user_id": "34890"
    },
}

/*
*search_key_like
*/

function search_key_like($value, $key, $array) {
     $results=array();
    $keyword = preg_quote($value, '~');
   foreach ($array as $k => $val) {
//if name a is spell John and keyword is sent as joh or JOH it will return null
//to fix the issue convert the string into lowercase and uppercase
       $data=array($val[$key],strtolower($val[$key]),strtoupper($val[$key]));
       if (preg_grep('~' . $keyword . '~', $data)) {
       array_push($results,$val[$key]);
    }
   }
   return $results;
}

用法===拉取JSON文件===

  $user_list_json='./user_list.json';
    if(file_exists($user_list_json) && file_get_contents($user_list_json)){
    $file_json_data=file_get_contents($user_list_json);

    $json_array_data=json_decode($file_json_data,true);

        $user_name_like = search_key_like('ron', 'name', $json_array_data);

         print "<pre>".print_r($user_name_like,true);
    }

原文由 ShapCyber 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题