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

Php 如何用另一个数组中的值替换数组中的值?,php,arrays,Php,Arrays,我正在获取一个数组: $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;

我正在获取一个数组:

$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;
}
状态字段中的值可以是0,1,2。我想用
$dict
中的值替换
$row
的key=state中的值,因此0=>A,1=>B,2=>C。state字段中的值等于$dict数组的位置
例如,如果
$row=[“id”=>“1”,“name”=>“john”,“state”=>“1”]

新的
$row=[“id”=>“1”,“name”=>“john”,“state”=>“B”]

您可以这样使用:

$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++;
}
$rows[$i]['state'] =  (isset($dict[$value['state']]) ? $dict[$value['state']] : ''); // if not set than empty anything else that you want.
如果您的
$dict
索引被固定为三个索引,那么它将完美工作

说明:

$dict[$value['state']]
这将根据索引值获取值

与如果
$value['state']==1类似,它将从
$dict
数组中获得“B”

为了安全起见,您也可以这样使用:

$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++;
}
$rows[$i]['state'] =  (isset($dict[$value['state']]) ? $dict[$value['state']] : ''); // if not set than empty anything else that you want.

$dict
数组中,已经有了作为键值对的精确映射。巧合的是,但仍然…我想知道为什么它被否决了…?它对我来说很好,我只是把$value换成了$row。