3

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
)
1
  • you could flatten the array. there are a ton of example on SO about doing just that. Commented Sep 1, 2011 at 20:50

6 Answers 6

4

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 ) 
Sign up to request clarification or add additional context in comments.

Comments

2

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>";

Comments

2
foreach ($lines as $inner) {
    $items[] =  $inner;
}

this ll work fine

Comments

1

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

Comments

1

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.