如何用另一个数组中的值替换数组中的值?
问题描述:
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"]
答
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.