PHP: Grouping array values by keys

杀马特。学长 韩版系。学妹 提交于 2019-12-11 10:09:21

问题


I have three array like this:

array1(
   0=>'title 1',
   1=>'title 2'
)

array2(
   0=>'description 1',
   1=>'description 2'
)

array3(
   0=>'price 1',
   1=>'price 2'
)

There is a php function to grouping array values by keys like this?

array(
   0=>array(title 1, description 1, price 1),
   1=>array(title 2, description 2, price 2),
)

回答1:


array_map(null, $array1, $array2, $array3)

See http://php.net/manual/en/function.array-map.php example #4.




回答2:


$pool =array();
foreach ( array_map(null, $array1, $array2, $array3) as $key => $value) {
    $pool[$key] = implode(", ", $value);
}
print_r($pool);

Result :

Array
(
    [0] => title 1, description 1, price 1
    [1] => title 2, description 2, price 2
)



回答3:


Try this code.

$array3 = array();
foreach ( $array1 as $key => $val ) {
    if ( !isset($array3[$val]) )
        $array3[$val] = array();

    $array3[$val][] = $array2[$key];
}

print_r($array3);


来源:https://stackoverflow.com/questions/21512889/php-grouping-array-values-by-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!