How to implode subarrays in a 2-dimensional array?

前端 未结 3 1030
时光说笑
时光说笑 2020-12-06 23:56

I want to implode values in to a comma-separated string if they are an array:

I have the following array:

$my_array = [
    \"keywords\" => \"test         


        
相关标签:
3条回答
  • 2020-12-07 00:11

    Just create a new array and set the elements (-;

    <?php
    ...
    $new_array = [];
    foreach ($my_array as $key => $value)
         $new_array[$key] = is_array($value) ? implode(",", $value) : $value;
    
    0 讨论(0)
  • 2020-12-07 00:24

    Just append values to new array:

    $my_array = [
       "keywords" => "test",
       "locationId" => [ 0 => "1", 1 => "2"],
       "industries" => "1",
    ];
    $new_Array = [];
    foreach ($my_array as $value) {
        $new_Array[] = is_array($value) ? implode(",", $value) : $value;
    }
    print_r($new_Array);
    

    And something that can be called a "one-liner"

    $new_Array = array_reduce($my_array, function($t, $v) { $t[] = is_array($v) ? implode(",", $v) : $v; return $t; }, []);
    

    Now compare both solutions and tell which is more readable.

    0 讨论(0)
  • 2020-12-07 00:35

    You don't need to write/iterate a conditional statement if you type the strings (non-arrays) as single-element arrays before imploding them.

    With array_map(): (Demo)

    $my_array = [
        "keywords" => "test",
        "locationId" => [ 0 => "1", 1 => "2"],
        "industries" => "1"
    ];
    
    var_export(
        array_map(
            function($v) {
                return implode(',', (array)$v);
            },
            $my_array
        )
    );
    

    Or from PHP7.4, array_map() with arrow function syntax: (Demo)

    var_export(
        array_map(fn($v) => implode(',', (array)$v), $my_array)
    );
    

    Or array_walk() and modification by reference (Demo)

    array_walk(
        $my_array,
        function(&$v) {
            $v = implode(',', (array)$v);
        }
    );
    var_export($my_array);
    

    Or a foreach loop: (Demo)

    foreach ($my_array as &$v) {
        $v = implode(',', (array)$v);
    }
    var_export($my_array);
    

    All snippets will output:

    array (
      'keywords' => 'test',
      'locationId' => '1,2',
      'industries' => '1',
    )
    
    0 讨论(0)
提交回复
热议问题