Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a flat array from the column values of a 2d array [duplicate]

Tags:

arrays

php

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");
$data2 = array("dog", "cow");
print_r(array_merge($data1, $data2));

That worked fine, but with the code I am using below, how may I achieve the desired output I am looking for?

$filename = "item.txt";
$lines = array();
$file = fopen($filename, "r");

while(!feof($file)) {
    $lines[] = explode("\t", fgets($file));
}   
fclose ($file);

foreach ($lines as $inner){
    $item = array($inner[1]);

    echo "<pre>";
    print_r($item);
    echo "</pre>";
}

My current output is:

Array
(
    [0] => Item one
)

Array
(
    [0] => Item two
)

Array
(
    [0] => Item three
)

Array
(
    [0] => Item four
)

Desired output would be:

Array
(
    [0] => Item one
    [1] => Item two
    [2] => Item three
    [3] => Item four
)
like image 351
Gdsmk Avatar asked Jul 23 '26 17:07

Gdsmk


1 Answers

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 ) 
like image 132
rlemon Avatar answered Jul 26 '26 09:07

rlemon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!