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

如何在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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?