Cesar Bielich
Cesar Bielich

Reputation: 4945

mysql/php - merge multiple arrays from mysql output in while statement

I need to merge many arrays from a mysql DB I have. The amount of arrays can vary. I am serializing the data into the DB and unserializing it on the way out. Where I am stumped is trying to use array_merge but not sure how to get the data into it properly.

For instance I have

$sql_get_votes_data = "SELECT * FROM algo_users WHERE data LIKE '%$movie_id%'";
$result_get_votes_data = mysql_query($sql_get_votes_data);
$final_array = array();
while($row_get_votes_data = mysql_fetch_array($result_get_votes_data)) {
    $final_array[] = unserialize($row_get_votes_data['data']);
}

Ultimately I need to be able to do a unique merge like this.

array_unique(array_merge($final_array1,$final_array2), SORT_REGULAR);

But since I have to place each array into a seperate variable in order to pass into array_merge I am not sure how to do that from the mysql call.

Any help would be awesome.

Upvotes: 1

Views: 1666

Answers (2)

fpierrat
fpierrat

Reputation: 804

Why not merge every new array while you're still in your loop?

$mergedArray=array();
while($row_get_votes_data = mysql_fetch_array($result_get_votes_data)) {
    $final_array = unserialize($row_get_votes_data['data']);
    $mergedArray=array_merge($mergedArray,$final_array);
}
array_unique($mergedArray, SORT_REGULAR);

Or if you need to keep track of your individual arrays:

$mergedArray=array();
$i=0;
while($row_get_votes_data = mysql_fetch_array($result_get_votes_data)) {
    $final_array[$i] = unserialize($row_get_votes_data['data']);
    $mergedArray=array_merge($mergedArray,$final_array[$i]);
    $i++
}
array_unique($mergedArray, SORT_REGULAR);

EDIT: I first understood you just wanted all arrays to be merged to a single array. The above edited answer now also removes duplicate entries as I now understand you wish.

Upvotes: 2

VolkerK
VolkerK

Reputation: 96159

You can e.g. use call_user_func_array for that.

<?php
$myarrs = array();

$result = call_user_func_array( 'array_merge', $myarrs); var_dump($result);

$myarrs[] = array(1,2,3);
$result = call_user_func_array( 'array_merge', $myarrs); var_dump($result);

$myarrs[] = array(4,5,6);
$result = call_user_func_array( 'array_merge', $myarrs); var_dump($result);

$myarrs[] = array(7,8,9);
$result = call_user_func_array( 'array_merge', $myarrs); var_dump($result);

but maybe it's more feasible to restructure the database and not to put the serialized arrays but single fields into the tables o the database can do the sorting/filtering/merging.

Upvotes: 0

Related Questions