dongshan0202405 2015-05-08 13:56
浏览 47
已采纳

每个用变量键获取一个值

I find it hard to explain but my page has a multidimensional array with all the users and I need to get values from the inner arrays without knowing the main key.

I'm not as experienced with arrays yet and I'm completely stuck right now. The function I use has 2 parameters. The first one is the input id of the user and the second is the array of the complete user list.

function userInfo($i, $users){
    foreach($users['data'] as $user){
        if($i = $user['id']){
            return $user['SOMENAME?']['name'];
        }
    }
}

Here is a example of the array I'm working with:

{
   "data": {
      "Doe": {
         "id": 266,
         "title": "Doe title",
         "name": "Doe",
         "key": "Some key"
      },
      "John": {
         "id": 412,
         "title": "John title",
         "name": "John",
         "key": "Some key"
      }
}

The function I have now simply returns Doe (The first value in the array) no matter how much arrays are in there.

How do I return the title or any of the other values when I don't know the name of the main key for that specific array?

  • 写回答

4条回答 默认 最新

  • dsa89029 2015-05-08 13:59
    关注

    There is an error in your if statement, where you are assigning a value, not ccomparing it (= vs == or ===).

    For the purpose of your function, I don't think you need to know the key, because you're already in the array. eg.

     function championInfo($i, $users){
         foreach($users['data'] as $index => $user){
            if($i == $user['id']){
                return $user['name'];
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?
  • ¥15 讲解电路图,付费求解