Matt Toner Matt Toner - 1 year ago 100
PHP Question

PHP Multidimensional Array Merge Issue

I am running a query that outputs a multidimensional array like this: -

Array
(
[0] => Array
(
[0] => Array
(
[id] => 772
[display_name] => Test Company Ltd
[profile_page] => partners/test-company
)

)

[1] => Array
(
)

[2] => Array
(
[0] => Array
(
[id] => 772
[display_name] => Test Company Ltd
[profile_page] => partners/test-company

)

)


I am trying to make the Array look like this so that we can loop through it on our site: -

Array
(
[0] => Array
(
[id] => 772
[display_name] => Test Company Ltd
[profile_page] => partners/test-company
)
)


This is all being generated using PHP using Symfony2 and Doctrine2. I have tried a couple of methods to get this working but I have reverted back to my first method which is this: -

$companies = array();

foreach($postcodes as $key=>$value) {
$conn = $em->getConnection();

$query = $conn->prepare("SELECT a.id, a.display_name, a.profile_page, b.meta_data FROM companies a, `cms`.pages b WHERE b.slug = a.profile_page AND a.active = 1 AND a.postcode = ".$value." ORDER BY a.display_name ASC");
$execute = $query->execute();
$companies[] = array_replace_recursive($query->fetchAll());
}

echo '<pre>'; print_r($companies); echo '</pre>';

die();


If someone can show me how to get around this, that would be great.

Answer Source

$query->fetchAll() is itself is an multidimensional array you're in need.

Just replace following line

$companies[] = array_replace_recursive($query->fetchAll());

with

$innCompnies=$query->fetchAll();
foreach($innCompnies as $inComp) {
     $companies[]=$inComp;
}

It wasn't working because you were pushing multidimensional array into another array. What we actually need to do is to push element one by one into the main array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download