mysticalghoul
mysticalghoul

Reputation: 672

Php: array merge

I am relatively new to php Sorry if I am not asking the question properly. here it goes:

My array:

$value = array(
        array('2500'),
        array('3000'),
        array('3500'),
        array('4000')
    );

From code:

$Array = array();
for ($i=0; $i<count($value);$i++) {
    $Array[]=$value;
} 
echo '<pre>';   
print_r($Array);
echo '</pre>';

How to merge it into one array like this:

Array
    [0] => 2500
    [1] => 3000
    [2] => 3500
    [3] => 4000
)

I've tried a lot of codes from array_merge to array_combine nothing seems to do the trick. Is their something I am missing in the code or is there a function or a filter that can accomplish this.

Thanks

Upvotes: 0

Views: 129

Answers (4)

Zoondia Development
Zoondia Development

Reputation: 1

You can try this

$output = array_column($value, 0);
print_r($output);

Upvotes: 0

Progrock
Progrock

Reputation: 7485

You can use foreach to iterate through an array.

<?php

$data = array(
    array('2500'),
    array('3000'),
    array('3500'),
    array('4000')
);

$output = [];
foreach($data as $value) {
    $output[] = $value[0];
}

var_dump($output);

Output:

array (size=4)
  0 => string '2500' (length=4)
  1 => string '3000' (length=4)
  2 => string '3500' (length=4)
  3 => string '4000' (length=4)

You could alternatively run a function on each member of the array using array_map. array_pop returns the last element 'popped' off each sub-array.

$output = array_map('array_pop', $data);
var_dump($output);

Output:

array (size=4)
  0 => string '2500' (length=4)
  1 => string '3000' (length=4)
  2 => string '3500' (length=4)
  3 => string '4000' (length=4)

Upvotes: 1

Michael Eugene Yuen
Michael Eugene Yuen

Reputation: 2528

Try this:

<?php
$value = array(
        array('2500'),
        array('3000'),
        array('3500'),
        array('4000')
    );

echo '<pre>'; // for display purpose only
print_r($value); // for display purpose only
$array = array();
if (is_array($value)) {
    foreach ($value as $v) {
        $array = array_merge($array,$v);
    }
} else {
    $array = array($value);
}

print_r($array); // for display purpose only

EDITED based on OP's update

http://www.phpwin.org/s/ib6dOO

Upvotes: 2

drakonli
drakonli

Reputation: 2414

change

$Array[]=$value;

to

$Array[]=array_merge($value, $Array);

Upvotes: 1

Related Questions