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 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用