convert 2d array to a string using php

前端 未结 5 1355
攒了一身酷
攒了一身酷 2021-01-22 06:39

I have the following array

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

I want to convert a string like the following:

         


        
相关标签:
5条回答
  • 2021-01-22 07:10

    I'm assuming that you have this array:

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

    In which case, you can do this:

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

    See it working

    0 讨论(0)
  • 2021-01-22 07:20
    $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), ',')));
    
    0 讨论(0)
  • 2021-01-22 07:20

    Looking at the solutions proposed so far, only one actually generates the correct output requested by the OP.

    So, stealing unashamedly from salathe's neat conversion, but with a transpose to provide the correct result:

    $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), ','))); 
    
    0 讨论(0)
  • 2021-01-22 07:24

    Given your array as $myArray, like this:

    $newArray = array();
    foreach ($myArray as $row) {
        $rowValue = implode(',', $row);
        $newArray[] = $rowValue;
    }
    $finalString = implode('|', $newArray);
    
    0 讨论(0)
  • 2021-01-22 07:29
    $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);
    
    0 讨论(0)
提交回复
热议问题