douxuanjie2692
2015-05-02 04:26
浏览 38
已采纳

如何在PHP中使用分隔符连接两个数组?

My graph is not getting generated properly with Chartist graph library It wants data generated as series: [ [2,4,5,5,6], [6,4,8,7] ] I tried to do it with this

 <?php echo "[". $comma_separated."],[". $comma_separated1."]"?>

$comma_separated = [2,4,5,5,6] $comma_separated1 = [6,4,8,7]

and I want $result = [ [2,4,5,5,6] , [6,4,8,7] ]

but only first array gets displayed in graph not second one ie $comma_separated1. Static entry of these things is generating it properly.

Is there any way that I can join these two strings into a single one with a "],[" between them and not between the contents in array.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doushang8512 2015-05-02 04:34
    已采纳

    Instead of creating the string manually, if both are already in array form, just use json_encode, you wouldn't need to manually add each string if the batches continue to grow:

    // example input
    $comma_separated = array(1, 2, 3, 4, 5); // 1 - 5
    $comma_separated2 = array(6, 7, 8, 9, 10); // 6 - 10
    
    $result = json_encode(array($comma_separated, $comma_separated2));
    echo $result; // [[1,2,3,4,5],[6,7,8,9,10]]
    

    Sample Output

    The example above parses them from an array form into string. If the input came from a string form (literal comma delimited string), then you need to explode it first, then cast all elements with int, so that in turn json_encode will treat them as int:

    // example input
    $comma_separated = '1,2,3,4,5';
    $comma_separated2 = '6,7,8,9,10';
    // int casting
    $comma_separated = array_map('intval', explode(',', $comma_separated));
    $comma_separated2 = array_map('intval', explode(',', $comma_separated2));
    
    $result = json_encode(array($comma_separated, $comma_separated2));
    echo $result; // [[1,2,3,4,5],[6,7,8,9,10]]
    

    Sample Output 2

    点赞 打赏 评论
  • donmqryh49993 2015-05-02 04:37

    Hope the mentioned helps you.

    <?php
    
    $array1 = array('2','4','5','5','6');
    $array2 = array('6','4','8','7');
    
    $finalString = array($array1, $array2);
    
    print "<pre>";
    print_r($finalString);
    print "</pre>";   
    
    ?>
    
    点赞 打赏 评论

相关推荐 更多相似问题