Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/247.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何将数组的值合并为数组相似键的逗号分隔字符串_Php_Arrays - Fatal编程技术网

Php 如何将数组的值合并为数组相似键的逗号分隔字符串

Php 如何将数组的值合并为数组相似键的逗号分隔字符串,php,arrays,Php,Arrays,我正试图从上面的数组中实现这一点 I have this array. $test['color'][0] = "red"; $test['color'][1] = "blue"; $test['color'][2] = "black"; $test['plug'][3] = "US"; $test['plug'][4] = "UK"; 实现这一点的最佳逻辑是什么。您可以很好地使用一些逻辑和一些PHP函数: $test2['color'] = "red,blue,black"; $test

我正试图从上面的数组中实现这一点

I have this array.

$test['color'][0] = "red";
$test['color'][1] = "blue";
$test['color'][2] = "black";
$test['plug'][3] = "US";
$test['plug'][4] = "UK";

实现这一点的最佳逻辑是什么。

您可以很好地使用一些逻辑和一些PHP函数:

$test2['color'] = "red,blue,black"; 
$test2['plug'] = "US,UK";
$test2['color'] = implode(',', $test['color']);
$test2['plug'] = implode(',', $test['plug']);

print_r($test2);

编辑:第一个答案是错误的,过于复杂。这是一个单一控制结构解决方案。

谢谢Fluffeh。$keys数组有什么用?@分号什么keys数组?在原始答案中?天知道,今天喝得太多了呵呵。我回头看了看我写的答案,几乎是面带微笑——因此编辑:)
<?php

    $array['color'][0] = "red";
    $array['color'][1] = "blue";
    $array['color'][2] = "black";
    $array['plug'][3] = "US";
    $array['plug'][4] = "UK";
    $test2=array();
    foreach($array as $key=>$val)
    {
        $test2[$key]=implode(',',$val);
    }

    print_r($test2);
?>
Array
(
    [color] => red,blue,black
    [plug] => US,UK
)