php - How to merge array elements with comma separated value without using explode function

446

I want to merge array elements into comma separated values. This is an array

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"
        ]
    ]
]

My expected array should be like this

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"
        ]
    ]
]

Need to merge New Project and Project in one position from array 2

251

Answer

Solution:

You can use this snippet of array_walk,

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

Demo.

288

Answer

Solution:

use 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']);
 }

People are also looking for solutions to the problem: php - Route in dingo not work when make Api with dingo/api and laravel 5.1

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.