如何通过不使用爆炸功能将数组转换为逗号

时间:2019-06-25 13:30:20

标签: php arrays laravel

我想将数组转换为逗号分隔的值。 我已经使用雄辩的关系来获取数据。 多维到逗号分隔的值

array:12 [
    0 => array:2 [
        "name" => "A1"
        "project" => array:1 [
            0 => "New Project"
        ]
    ]
    1 => array:2 [
        "name" => "A2"
        "project" => array:2 [
            0 => "New Project"
            2 => "Project"
        ]
    ]
]

我想要这样的数组

array:12 [
    0 => array:2 [
        "name" => "A1"
        "project" => array:1 [
            0 => "New Project"
        ]
    ]
    1 => array:2 [
        "name" => "A2"
        "project" => array:2 [
            0 => "New Project","Project"
        ]
    ]
]

我想将“新项目”和“项目”合并到数组2中的一个位置

2 个答案:

答案 0 :(得分:2)

您可以使用array_walk的这段代码,

array_walk($arr, function(&$val){
    $val['project'] = implode(",", $val['project']);
});

Demo

答案 1 :(得分:0)

使用implode

$arr = array:12 [
     0 => array:2 [
        "name" => "A1"
      "project" => array:1 [
            0 => "New Project"
          ]
        ]  
       1 => array:2 [
         "name" => "A2"
          "project" => array:2 [
               0 => "New Project"
               2 => "Project"
           ]
      ]


foreach ($arr as &$value) {
   implode(', ', $value['project']);
 }