开发者

how to merge these 2 arrays (php+sql)

I have 2 arrays, both from a SQL query, each from a different database. Since it's not possible to merge these 2 SQL queries into 1 query to get 1 array (due to some restrictions), I am forced to combine the 2 arrays. Problem is, I can't seem to get this working.

This is array 1:

echo '<ul id="friends">';
    foreach($result as $friend => $value)
        {
            echo '<li><img src="'.$value['pic_square'].'" alt="" />'.$value['uid'].' ' . $value['name'] . '</li>';
        }
    echo '</ul>';

And wi开发者_C百科ll output:

  • picture 12345 Dave
  • picture 67890 Mike
  • Etc

This is array 2:

echo '<ul id="friends">';
    while($value = mysql_fetch_array($query))
        {
        echo '<li> '.$value['fbid'] .' '. $value['userphone'] .'</li>';

        }
    echo '</ul>';

And will output:

  • 12345 020-12345
  • 67890 020-56789
  • Etc

What do I need? I want to merge these 2 arrays so that the phonenr from array 2 will be added behind the username from array 1.

Example what the output should look like:

  • picture Dave 020-12345
  • picture Mike 020-56789
  • Etc

fbid and uid are the id's to link each other, but are not shown in the combined array.

Hope someone knows how to do this!

Kind regards,

Maurice


This is the simplest and most efficient way I could think of doing it. The foreach loop iterates through your first array and basically add new key/value pairs using the "uid" as the key. This will enable you to easily find them when you loop through the second query's results.

<?php

// First query.
foreach ( $result as $key => $value )
{
  // Add a new key/value pair in the array using the "uid" as the key and $value as the value.
  $result[$value['uid']] = $value;

  // Remove the previous key/value pair value.
  unset($result[$key]);
}

// Second query.
while ( $value = mysql_fetch_array($query) )
  echo sprintf('<li>%s %s %s</li>', $result[$value['fbid']]['pic_square'], $result[$value['fbid']]['name'], $value['userphone']);


As the array collection names are different (different column name) I am not sure direct merging will work.

$result = array_merge($result, $query);
print_r($result);

But you can work around like below.

Give loops and store in a third array from both the arrays and do necessary actions on third array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜