How to merge an array inside another array in php? - php

Im trying to merge or put an Array (called '$rows_ban') inside a sub item of another array (called '$rows') in a final array named '$rows_final'.
Im using array_merge but returns null inside 'data':
{"date":"2018-05-03","hour":"09:12:32","data":[null]}
It should return the results in of the second query inside the 'data':
{"date":"2018-05-03","hour":"09:12:32","data":[{...},{...},{...}]}
PHP Script:
$rows = array();
$rows_ban = array();
$rows_final= array();
$result1 = mysqli_query($link,"SELECT `id`,`sync_date`,`sync_time` FROM sync_log");
while($r = mysqli_fetch_array($result1)) {
$rows['date']= $r[2];
$rows['hour']= $r[3];
$rows['data'][]= null;
}
$result2 = mysqli_query($link,"SELECT cod, name, total from totals " );
while($r = mysqli_fetch_array($result2)) {
$rows_ban['cod'] = $r[0];
$rows_ban['name'] = $r[1];
$rows_ban['total'] = $r[2];
$result3 = mysqli_query($link,"SELECT *, 1 as Filter from
table3 where cod=".$r[0]." order by dates desc");
while($r = mysqli_fetch_assoc($result3)) {
$rows_ban['sub_data'][] = $r;
}
$rows_final = array_merge($rows['data'],$rows_ban);
// here im trying to merge the $rows_ban array inside the
$rows['data']
}
echo json_encode($rows_final);

Not sure if that's what you wanted to accomplish since your description is very poor and hard to understand.
$output = [];
$tmpRows = [];
$result = mysqli_query($link, 'SELECT `id`,`sync_date`,`sync_time` FROM sync_log');
if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$output['date'] = $tmp[0]['sync_date'];
$output['time'] = $tmp[0]['sync_time'];
}
$result = mysqli_query($link, 'SELECT cod, name, total from totals ');
if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$tmpRows['cod'] = $tmp[0]['cod'];
$tmpRows['name'] = $tmp[0]['name'];
$tmpRows['total'] = $tmp[0]['total'];
$result = mysqli_query($link,"SELECT *, 1 as Filter from
table3 where cod={$tmp[0]['cod']} order by dates desc");
if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$tmpRows['sub_data'] = $tmp[0];
}
$output['data'] = $tmpRows;
}
print_r(json_encode($output));
Also array_merge doesn't work like you think it does. It returns merged array like it's name states. Regarding to your code, final result would be exactly $rows_ban encoded to json.
http://php.net/manual/en/function.array-merge.php

Related

PHP Creating an array inside a For Loop

Looking for some help if possible.
$pilotsids is an array of ids.
merged is the table that holds the data.
For each pilotid, I'd like to create an array of newrat values, which I am going to use later to populate a chart. The index of the for loop must be added to the name of each array like this:
$data0[]
$data1[]
$data2[]...etc
It works when I do it separately:
$result = $mysqli->query("select newrat from merged where pilotid = $pilotids[0] order by mid asc");
while($row = mysqli_fetch_assoc($result)) {
$data0[] = $row['newrat'];
}
$result = $mysqli->query("select newrat from merged where pilotid = '$pilotids[1]' order by mid asc");
while($row = mysqli_fetch_assoc($result)) {
$data1[] = $row['newrat'];
}
$result = $mysqli->query("select newrat from merged where pilotid = '$pilotids[2]' order by mid asc");
while($row = mysqli_fetch_assoc($result)) {
$data2[] = $row['newrat'];
}
It doesn't if I try to to iterate automatically for lets say 10 times:
for($i=0; $i < 10; $i++) {
$result = $mysqli->query("select newrat from merged where pilotid = $pilotids[$i] order by mid asc");
while($row = mysqli_fetch_assoc($result)) {
${$data.$i}[] = $row['newrat'];
}
}
You can try this way:
$data = [];
for($i=0; $i < 10; $i++) {
$result = $mysqli->query("select newrat from merged where pilotid = $pilotids[$i] order by mid asc");
while($row = mysqli_fetch_assoc($result)) {
$data[$i][] = $row['newrat'];
}
}
As you can see I'm using a two dimensional array which is defined outside of the loop.

Merging arrays to the one array from while loop

I need an information to put from DB to arrays and then make one array.
So I wrote a following code:
$sql0 = "SELECT * FROM ".$working_table." ORDER by id ASC";
$result = mysqli_query($conn, $sql0);
$num_rows = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result)){
${"emails_arr$row[id]"} = explode(",",$row['station_email']);
echo print_r(${"emails_arr$row[id]"})."<br>";
}
$sql0 = "SELECT * FROM ".$working_table." ORDER by id ASC";
$result = mysqli_query($conn, $sql0);
$num_rows = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result)){
$result_array = array_merge(${"emails_arr$row[id]"});
}
echo print_r($result_array);
the tricky part is that i don't know how to merge an arrays to one array from the while loop: $result_array = array_merge(${"emails_arr$row[id]"});
it only shows the last array, other arrays are being rewrote.
Thank you guys!
Change your while loop code with this one
while($row = mysqli_fetch_array($result)){
$result_array[] = array_merge(${"emails_arr$row[id]"});
}
Notice the Square Brackets.

How to extract values from single database column / store in array

I am hoping someone can help me with this. I am trying to extract all the values from a single column of a database and store the returned values in a numeric array.
$num = 1;
$q = "SELECT `uninum` FROM `participants` WHERE `islecturer` = '".$num."'";
$result = #mysqli_query ($dbcon, $q);
$storeArray = array();
while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
$storeArray [] = $row['uninum'];
}
echo $storeArray [1];
The second parameter to mysqli_fetch_array sets the array type. You have set it to a numerical index. You want an associative index:
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { //correct flag
$storeArray [] = $row['uninum'];
}
Or just use the mysqli_fetch_assoc function instead:
while ($row = mysqli_fetch_assoc($result)) {
$storeArray [] = $row['uninum'];
}

Adding to an array from $row

How do I add each result from $row to the $valueIDArray? I then want to use the $valueIDArray to get results from a second database, how do I do that?
$sql = "SELECT * FROM venue
WHERE capacity >= 'partySize'";
//step 2 - executing the query
$result =& $db->query($sql);
if (PEAR::isError($sql)) {
die($result->getMessage());
}
while($row = $result -> fetchrow()){
$valueIDArray = $row[0];
}
You should do it this way:
$valueIDArray = array()
while($row = $result -> fetchrow()){
$valueIDArray[] = $row[0];
}
Define array before loop, and in loop simple add elements to array using [] after array name
$sql = "SELECT * FROM venue WHERE capacity >= 'partySize'";
//step 2 - executing the query
$result =& $db->query($sql);
if (PEAR::isError($sql)) {
die($result->getMessage());
}
$valueIDArray = array();
while($row = $result -> fetchrow()){
$valueIDArray[] = $row[0];
}
You have to add the [] braces. Like this, you always add another entry for the row.

problem of while loop and array

$result=array();
$table_first = 'recipe';
$query = "SELECT * FROM $table_first";
$resouter = mysql_query($query, $conn);
while ($recipe = mysql_fetch_assoc($resouter, MYSQL_ASSOC)){
$result['recipe']=$recipe;
$query2="SELECT ingredients.ingredient_id,ingredients.ingredient_name,ingredients.ammount FROM ingredients where rec_id = ".$recipe['rec_id'];
$result2 = mysql_query($query2, $conn);
while($ingredient = mysql_fetch_assoc($result2)){
$result['ingredient'] = $ingredient;
}
echo json_encode($result);
}
this code show me all the recipes but only the last ingredients i.e
{"recipe":{"rec_id":"14","name":"Spaghetti with Crab and Arugula","overview":"http:\/\/www","category":"","time":"2010-11-11 14:35:11","image":"localhost\/pics\/SpaghettiWithCrabAndArugula.jpg"},"ingredient":{"ingredient_id":"55","ingredient_name":"test","ammount":"2 kg"}}{"recipe":{"rec_id":"15","name":"stew recipe ","overview":"http:\/\/www","category":"","time":"2010-11-11 14:42:09","image":"localhost\/pics\/stew2.jpg"},"ingredient":{"ingredient_id":"25","ingredient_name":"3 parsnips cut into cubes","ammount":"11"}}
i want to output all the ingredient records relevant to recipe id 14 and this just print the last ingredient.
$result['ingredient'] = $ingredient;
Is replacing the variable $result['ingredient'] with the most recent $ingredient value each time, culminating with the last value returned, you should use:
$result['ingredient'][] = $ingredient;
To incrememnt/create a new value within the $result['ingredient'] array for each $ingredient. You can then output this array according to your needs. Using print_r($result['ingredient']) will show you its content...to see for yourself try:
while($ingredient = mysql_fetch_assoc($result2)){
$result['ingredient'][] = $ingredient;
}
print_r($result['ingredient']);
If I understand correctly what you want to do, there is a way to optimize the code a lot, by fetching recipes and ingredients in one single query using a JOIN :
$recipes = array();
$recipe_ingredients = array();
$query = "SELECT * FROM recipe LEFT JOIN ingredients ON ingredients.rec_id=recipe.rec_id ORDER BY recipe.rec_id DESC";
$resouter = mysql_query($query, $conn);
$buffer_rec_id = 0;
$buffer_rec_name = "";
$buffer_rec_cat = "";
while( $recipe = mysql_fetch_array($resouter) )
{
if( $buffer_rec_id != $result['recipe.rec_id'] )
{
$recipes[] = array( $buffer_rec_id, $buffer_rec_name, $buffer_rec_cat, $recipe_ingredients);
$recipe_ingredients = array( );
$buffer_rec_id = $result['recipe.rec_id'];
$buffer_rec_name = $result['recipe.rec_name'];
$buffer_rec_cat = $result['recipe.rec_category'];
}
else
{
$recipe_ingredients[] = array( $result['ingredient_id'], $result['ingredient_name'], $result['ammount'] );
}
}
$print_r($recipes);
This code should give you a multi-dimensional array that you can use later to get the data you want.
I let you adapt the code to have exactly the information you need.

Categories