且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将数组或对象的数组转换为关联数组?

更新时间:2022-02-11 23:56:46

几天前,我遇到了完全相同的问题。无法使用 array_map ,但是 array_reduce 可以解决问题。

I had the exact same problem some days ago. It is not possible using array_map, but array_reduce does the trick.

$arr = array('a','b','c','d');
$assoc_arr = array_reduce($arr, function ($result, $item) {
    $result[$item] = (($item == 'a') || ($item == 'c')) ? 'yes' : 'no';
    return $result;
}, array());
var_dump($assoc_arr);

结果:

array(4){[ a] => string(3)是 [ b] => string(2) no [ c] => string(3)是 [ d] => string(2) no}