在循环php上连接数组

时间:2018-02-10 04:02:52

标签: php arrays

我有这个数组

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

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

如何实现这种输出见下文。如果数组计数大于1,我想将它们合并为一个。

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

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

这是我的代码,但它没有工作

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

感谢

3 个答案:

答案 0 :(得分:2)

为什么不使用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];

结果:

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

答案 1 :(得分:1)

我想它会是这样的:

    <div class="container">
      <header>
        <h1>Srikanth Gowda</h1>
      </header>
    	
    <nav class="navbar">
    	<ul>
    		<li>Design</li>
    		<li>Photography</li>
    		<li>About</li>
    		<li>Contact</li>
    		<li>Blog</li>
    	</ul>
    </nav>
    </div>

答案 2 :(得分:1)

我想它会是这样的:

$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);