我有一个包含逗号分隔值的变量,如下所示:$str = "1,5";
要将其转换为数组,我有以下代码:
$str = "1,5";
$replacements = explode(',', $str);
现在数组如下所示:
Array
(
[0] => 1
[1] => 5
)
我有另一个数组:$base = array('1'=>'Bread','5'=>'Butter');
我要做的是根据关联数组的值和数字数组的值将数字数组的值替换为上面key
的关联数组的值,它应该如下所示:
// This is what I am trying to achive
Array
(
[0] => Bread // because 1 = Bread in the assoc. array
[1] => Butter // because 5 = Butter in the assoc. array
)
为了实现这一点,我尝试了以下代码:
$str = "1,5";
$replacements = explode(',', $str);
$base = array('1'=>'Bread','5'=>'Butter');
$basket = array_replace($base, $replacements);
print_r($basket);
但它给了我以下输出:
Array
(
[1] => 5
[5] => Butter
[0] => 1
)
你能告诉我如何解决这个问题吗?