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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里