简体   繁体   中英

Concatenate array on loop php

I have this array

[0] => Array
        (
            [0] => My name
            [1] => is
            [2] => John
        )

[1] => Array
        (
            [0] => My name is Jane
        )

how to achieve this kind of output see below. If the array count is greater than one I want to combine them as one.

[0] => Array
        (
            [0] => My name is John
        )

[1] => Array
        (
            [0] => My name is Jane
        )

here is my code but it didn't work

foreach ($myArr as $key => $value) {
    if (count($myArr[$key]) > 1) {
        foreach ($value as $k => $v) {
            $myArr[$key] .= $v; 
        }
    }
}

thanks

Why not use implode?

$data = [['my name', 'is', 'John'],['my name is Jane']];
$results = [];
foreach ($data AS $id=>$datum)
    if (count($datum) > 1)
        $results[$id] = implode($datum, ' ');
    else
        $results[$id] = $datum[0];

results:

array(2) {
  [0]=>
  string(15) "my name is John"
  [1]=>
  string(15) "my name is Jane"
}

I suppose it would be like this:

foreach ($myArr as $key => $value) {
    if (count($myArr[$key]) > 1) {
        $myArr[$key][0] = '';  
        foreach ($value as $k => $v) {
            $myArr[$key][0] .= $v; 
        }
        array_splice($myArr[$key], 1, count($myArr[$key])-1);
    }
}

I suppose it would be like this:

$ary[0] = Array("My name","is","John");
$ary[1] = Array( "My name is Jane" );
$i=0;       
foreach ($ary as $ar_item)  {
    $merged="";
foreach  ($ar_item as $ar_subitem)  
{
    $merged=$merged.$ar_subitem." ";
}
$ary[$i]=$merged;
$i++;
}
var_dump($ary);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM