使用php将2d数组转换为字符串

时间:2012-01-06 12:26:02

标签: php

我有以下数组

 01 03 02 15
 05 04 06 10
 07 09 08 11
 12 14 13 16

我想转换如下字符串:

 01,05,07,12|03,04,09,14|02,06,08,13|15,10,11,16

任何人都可以告诉我该怎么做,任何帮助将不胜感激!

5 个答案:

答案 0 :(得分:7)

我假设你有这个数组:

$array = array (
  array ('01','03','02','15'),
  array ('05','04','06','10'),
  array ('07','09','08','11'),
  array ('12','14','13','16')
);

在这种情况下,你可以这样做:

$tmpArr = array();
foreach ($array as $sub) {
  $tmpArr[] = implode(',', $sub);
}
$result = implode('|', $tmpArr);
echo $result;

See it working

答案 1 :(得分:2)

$input = array(
    array('01', '02', '03', '04'),
    array('11', '12', '13', '14'),
    array('21', '22', '23', '24'),
    array('31', '32', '33', '34'),
);
$newArray = array();
foreach($input as $rowIndex => $row) {
    foreach($row as $key => $val) {
        if(!$newArray[$key]) {
            $newArray[$key] = array();
        }
        $newArray[$key][$rowIndex] = $val;
    }
}
$strRows = array();
foreach($newArray as $key => $row) {
    $strRows[$key] = join(',', $row);
}
$output = join('|', $strRows);

答案 2 :(得分:1)

$input = array (
    array ('01','03','02','15'),
    array ('05','04','06','10'),
    array ('07','09','08','11'),
    array ('12','14','13','16'),
);

echo implode('|', array_map('implode', $input, array_fill(0, count($input), ',')));

答案 3 :(得分:0)

将您的数组指定为$ myArray,如下所示:

$newArray = array();
foreach ($myArray as $row) {
    $rowValue = implode(',', $row);
    $newArray[] = $rowValue;
}
$finalString = implode('|', $newArray);

答案 4 :(得分:0)

查看到目前为止提出的解决方案,实际上只有一个生成OP请求的正确输出。

所以,从salathe的整洁转换中毫不羞愧地偷走,但是通过转置来提供正确的结果:

$input = array ( 
    array ('01','03','02','15'), 
    array ('05','04','06','10'), 
    array ('07','09','08','11'), 
    array ('12','14','13','16'), 
); 

function transpose($array) {
    array_unshift($array, null);
    return call_user_func_array('array_map', $array);
}

$transposed = transpose($input);

echo implode('|', array_map('implode', $transposed, array_fill(0, count($transposed), ',')));