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.
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.
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.
Related
I have this query:
$all = $dbh->query("SELECT DISTINCT movimenti.nome, SUM(movimenti_carta.importo)
FROM movimenti_carta JOIN movimenti ON movimenti_carta.movimento=movimenti.id
WHERE month(data)='$mese' AND year(data)='$anno' GROUP BY movimenti.nome");
It retrieves two columns from my db. What I want to do is to put each column in a separate array.
If I do:
$labels=$all->fetchAll(PDO::FETCH_COLUMN,0);
I get the values for the first column with the format I am looking for.
I tried to do:
$values=$all->fetchAll(PDO::FETCH_COLUMN,1);
after the first fetch but $all is unset by the first fetch and the result is that $values is an empty array (I was pretty sure of this but did give it a try).
I can build the arrays in php after I fetch an array with both columns but I was wondering how to get my goal using PDO api.
Of course it will never work this way, as fetchAll() returns data only once.
The only idea I could think of is PDO::FETCH_KEY_PAIR constant:
$data = $all->fetchAll(PDO::FETCH_KEY_PAIR);
$labels = array_keys($data);
$values = array_values($data);
It feels like you are overcomplicating this. It's easily done in PHP, and if you just use PDOStatement::fetch, you don't need to worry about array manipulation; it will also be more friendly to your memory usage if you have a lot of data.
$labels = [];
$values = [];
while ($row = $all->fetch(PDO::FETCH_NUM)) {
$labels[] = $row[0];
$values[] = $row[1];
}
Maybe you could use array_column.
$all = $dbh->query("
SELECT DISTINCT movimenti.nome, SUM(movimenti_carta.importo) AS importo
FROM movimenti_carta
JOIN movimenti ON movimenti_carta.movimento=movimenti.id
WHERE month(data)='$mese'
AND year(data)='$anno'
GROUP BY movimenti.nome
");
// set of results indexed by column name
$results = $all->fetchAll(PDO::FETCH_ASSOC);
// set of values from the column 'nome'
$nomes = array_column($results, 'nome');
// set of values from the column 'importo'
$importos = array_column($results, 'importo');
I can't seem to find a way to save all rows from odbc_exec to an array. I found php_fetch_array, but that only fetches one row at a time, requiring me to iterate through all rows to put it into an array. Is there a more concise way to do this?
Tried
`
$myArray = array();
while (odbc_fetch_row($result)) {
$myArray[odbc_result($result,1)] = odbc_result($result,2);
}`
and also
`
$myArray = array();
while ($myRow = odbc_fetch_row($result)) {
$myArray[$myRow['id']] = $myRow['name'];
}`
but $myArray is still empty.
What would be a direct way to turn comma separated data from a mysql table, into a simple php array, other than doing it like I'm doing now?
I current do this in a very messy way by selecting data, then concatenating it into a string, which I later use.
I'm using PDO here.
Data is simple
locations
-------------------
US,UK,SE,DE
DE,SE,CA
GB,US,DE,SE
AU,NZ,GB
pdo
$d = $db->prepare('select locations a from destinations');
$d->execute();
$d->bindColumn('a',$a);
$count = $d->rowCount();
if($count >= 1) {
$b = '';
while($row = $d->fetch()) {
$b .= $a.',';
}
} else {
$b = 'No records to display';
}
echo $b;
The output I'm hoping to achieve is just a simple array like below, which is all the rows joined together.
Desired output
array('US','UK','SE','DE','DE','SE','CA','GB','US','DE','SE','AU','NZ','GB')
Can you help?
You're almost there. The easiest thing you can do is use explode(',', $b) for the complete string you have now, and frankly, I'm a bit surprised that you couldn't figure that part out after writing all that code.
Instead of concating everying in PHP, you can also concat it in the query using the GROUP_CONCAT function. This will introduce a limit, though, since the result of GROUP_CONCAT can be at most 32k, if I remember correctly.
Below is an alternative approach. Here, each row is fetched and exploded to an array immediately. That array is merged with (appended to, actually) to one big resulting array.
The advantage is that you are not concatting a big string first, which is relatively inefficient, but in practice, I doubt if you can tell the difference in performance.
$d = $db->prepare('select locations a from destinations');
$d->execute();
// An array for results.
$results = array();
$d->bindColumn('a',$a);
$count = $d->rowCount();
if($count >= 1) {
$b = '';
while($row = $d->fetch()) {
// explode each row and append it to the array.
$results = array_merge($results, explode(',', $a));
}
} else {
$b = 'No records to display';
}
// Display the complete array.
print_r($results);
You could just select the entries and then turn them into arrays by "exploding" them like this:
$locationArray = explode(",", $databaseEntry);
This will seperate your database entries by comma and add each entry to the array.
Documentation: http://php.net/manual/de/function.explode.php
Hope I could help
I'm a bit new to multidimensional arrays, and would like to see if I'm doing it right. preferably, I'd like to name the arrays within the main array for ease of use.
$unique_array = array(
username=>array(),
user_id=>array(),
weeknumber=>array()
);
and then I have a while loop which checks some database results:
while($row = mysql_fetch_array($query)) //yes, I know mysql is deprecated
{
$unique_array[] = username=>$row['username'], user_id=>$row['user_id'], week number=>['weeknumber'];
}
I'm not sure if I am placing the values in the array from within the while loop correctly, or if it needs to be done some other way. I couldn't find any resources I could easily understand on SO or elsewhere to deal with query results within a named array within a multidimensional array.
EDIT FOLLOW UP QUESTION: I also need to check the array for duplicate values, because there will be multiple values that are exactly the same, but I only want one of them.
Any help is appreciated!
EDIT SOLUTION:
By modifying the answer I was able to create code to fit my needs.
Array initialization:
$unique_array = array(
'username'=>array(),
'user_id'=>array(),
'weeknumber'=>array()
);
Building the array from within a while loop:
while($row = mysql_fetch_array($query))
{
$unique_array[] = array('username'=>$row['username'], 'user_id'=>$row['user_id'], 'weeknumber'=>$row['weeknumber']);
}
And finally, I need to make sure the array values are unique (there are duplicates entries as a result of database and query limitations), after the while loop I have:
print_r(multi_unique($unique_array));
Is the top level an associative array or a numeric array?
If it is an associative array, it should have structure like this:
$unique_array = array(
'username'=>array('John','Mike',...),
'user_id'=>array(1,2,3,...),
'week_number'=>array(1,2,3,...)
);
Or if it is a numeric array, it should have structure like this:
$unique_array = array(
array('username'=>'John', 'user_id'=>1, 'week_number'=>1),
array('username'=>'Mike', 'user_id'=>2, 'week_number'=>2),
array('username'=>'Sam', 'user_id'=>3, 'week_number'=>3),
...
)
for the first type use the code below:
while ($row = mysql_fetch_assoc($query)) {
$unique_array['username'][] = $row['username'],
$unique_array['user_id'][] = $row['user_id'],
$unique_array['week_number'][] = $row['week_number'],
}
for the second type, it is something like your code. But there are some syntax problems:
while($row = mysql_fetch_array($query)) //yes, I know mysql is deprecated
{
$unique_array[] = array('username'=>$row['username'], 'user_id'=>$row['user_id'], 'week_number'=>$row['weeknumber']);
}
I'm trying to store data from a table, and I do not know how many lines will be in said table. My idea was to make a main array called data, a sub array for each line with just numeric labels (1,2,3,etc) and then inside each of those would be the actual data from each line, so it would be like this:
data
->1
->item1
->item2
->item3
->2
->item1
->item2
->item3
->3
->item1
->item2
->item3
ETC. I know how to work with multidimensional arrays and I know there are easy ways to accomplish this in java, but I can't for the life of me figure out how to do it in php.
To keep on adding to an array simply use the following code:
$myArray[] = 'another value';
Notice the [] this tells php to add another value to the array (without removing previous elements)
See here for a quick tutorial on mutidimensional arrays:
http://webcheatsheet.com/PHP/multidimensional_arrays.php
And this:
http://www.developerdrive.com/2012/01/php-arrays-array-functions-and-multidimensional-arrays/
Try,
foreach($rows as $v) {
$data[] = array($v['item1'], $v['item2'], $v['item3']);
}
To map mySQL data to a multidimensional array:
$query = mysql_query("SELECT * FROM table WHERE uid = '1' ORDER BY id DESC");
$results = array();
$i = 0;
while($line = mysqli_fetch_array($query, MYSQL_ASSOC)){
$results[$i] = $line;
$i++;
}