douju1928 2016-01-27 10:37
浏览 31
已采纳

如何用另一个数组中的值替换数组中的值?

I'm fetching an array:

$sql = SELECT id, name, state FROM table ORDER BY name
$result = mysqli_query($conn, $sql);
$rows = array();
$dict = ["A","B","C"];
while ($row = mysqli_fetch_array($result)) {
//replace state value here before next line
  $rows[] =  $row;
}

Values in the state field can be 0,1,2. I want to replace the value in key=state of $row with the value from $dict so 0=>A, 1=>B, 2=>C. Value in state field equals position of $dict array.
ex. if $row=["id"=>"1","name"=>"john", "state"=>"1"]
new $row=["id"=>"1","name"=>"john", "state"=>"B"]

  • 写回答

1条回答 默认 最新

  • 普通网友 2016-01-27 10:46
    关注

    You can use like that:

    $dict = array("A","B","C");
    $i = 0;
    while ($row = mysqli_fetch_array($result)) {
       $rows[$i]['id'] =  $row['id'];
       $rows[$i]['name'] =  $row['name'];
       $rows[$i]['state'] =  $dict[$value['state']];
       $i++;
    }
    

    If your $dict index is fixed into three index than it will work perfectly.

    Explanation:

    $dict[$value['state']] this will get the value as per index value.

    Like if $value['state'] == 1 than it will get the "B" from $dict array.

    For the safe hand you can also use like that:

    $rows[$i]['state'] =  (isset($dict[$value['state']]) ? $dict[$value['state']] : ''); // if not set than empty anything else that you want.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记