php merge arrays

前端 未结 6 1642
北海茫月
北海茫月 2021-01-21 08:33

I have been trying (unsuccessfully) to merge the output of multiple arrays into a single array. An example of what I tried was:

$data1 = array(\"cat\", \"goat\")         


        
相关标签:
6条回答
  • 2021-01-21 08:50

    using array_merge_recursive ::

    $arr1 = array("Item One");
    $arr2 = array("Item Two");
    print_r(array_merge_recursive($arr1, $arr2));
    

    outputs

    Array ( [0] => Item One [1] => Item Two ) 
    
    0 讨论(0)
  • 2021-01-21 08:54

    modify your last foreach loop to look like this:

    $output=array();
    foreach($lines as $inner){
        $output[]=$inner[1];
    }
    header('Content-type: text/plain; charset=utf-8');
    print_r($output);
    
    0 讨论(0)
  • 2021-01-21 08:55

    You could add the items to a new array sequentially to achieve your desired result:

    :
    $aResult = array();
    foreach ($lines as $inner) {
        $item = array($inner[1]);
        $aResult[] = $item;
    }
    var_dump($aResult);
    
    0 讨论(0)
  • 2021-01-21 08:56

    There may be a better way, but this should work. Just loop through and merge each array individually:

    $items = array();
    
    foreach ($lines as $inner){
        $item = array($inner[1]);
    
        $items = array_merge($items, $item);
    }
    
    echo "<pre>";
    print_r($items);
    echo "</pre>";
    
    0 讨论(0)
  • 2021-01-21 09:03
    foreach ($lines as $inner) {
        $items[] =  $inner;
    }
    

    this ll work fine

    0 讨论(0)
  • 2021-01-21 09:11

    Your example that works is completely different from your non working code. You are not even using array_merge in it.

    If you are only accessing scalar elements, the following will work, but does not use array_merge either:

    $items = array();
    foreach ($lines as $inner) {
        $items[] = $inner[1];
    }    
    $items = array_unique($items);
    
    echo "<pre>";
    print_r($items);
    echo "</pre>";
    

    If you are interested in all of $inner, than you would use array_merge:

    $items = array();
    foreach ($lines as $inner) {
        $items = array_merge($items, $inner);
    }
    
    0 讨论(0)
提交回复
热议问题