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.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 关于#html5#的问题:H5页面用户手机返回的时候跳转到指定页面例如(语言-javascript)
  • ¥15 无法使用此凭据登录,因为你的域不可用,如何解决?(标签-Windows)
  • ¥15 yolov9的训练时间
  • ¥15 二叉树遍历没有报错但无法正常运行
  • ¥15 在linux系统下vscode运行robocup3d上场球员报错
  • ¥15 Python语言实验
  • ¥15 SAP HANA SQL 增加合计行
  • ¥20 用C#语言解决一个英文打字练习器,有偿
  • ¥15 srs-sip外部服务 webrtc支持H265格式
  • ¥15 在使用abaqus软件中,继承到assembly里的surfaces怎么使用python批量调动