douju1928 2016-01-27 02: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 02: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.
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部