array_merge() How can I add a 'range' of an array name - php

I have a $nr variable that as the number of arrays with the same name that i created in a previous function, something like this:
$var = 'sorteios_'.$nr;
$$var = array($sorteio_id);
I have it in a While function so it was created something like 3 arrays with the names:
$sorteios_1 , $sorteios_2 , $sorteios_3
And i want to add them inside an array_merge, so i have to use the $nr that says how many arrays with the same name were created.
$nr = 3;
i want that the final result looks something like this.
$result = array_merge($sorteios_1, $sorteios_2, $sorteios_3);
That's the whole function if you want to check it (it's not complete because of the problem i'm having):
function check_sorteios(){
global $db;
$id = $_SESSION['userid'];
$query1 = "SELECT * FROM sorteios WHERE userid = $id";
$result1 = $db->query($query1);
$count = $result1->rowCount();
if ($count == 0){ $sorteios = 0; echo "sem sorteios";}
else{
$numero = 0;
$sorteios = 0;
$nr = 0;
while($row1 = $result1->fetch()){
if ( $numero == $count ){ return 0;}
$numero++;
$sorteio_id = $row1['id'];
$query2 = "SELECT * FROM productos WHERE id = $sorteio_id";
$result2 = $db->query($query2);
while($row2 = $result2->fetch()){
$data = $row2['data'];
$titulo = $row2['titulo'];
if (strtotime($data) > time()){
if(!isset($$sorteio_id)){
$$sorteio_id = 1;
}
$nr++;
$var = 'sorteios_'.$nr;
$$var = array($sorteio_id);
}
}
}
}
$result = array_merge($sorteios_1, $sorteios_2, $sorteios_3);
$occurences = array_count_values($result);
print_r($occurences);
}

You could try to create a string containing the code executing array_merge of all your arrays and then pass it to the eval function (http://it1.php.net/manual/it/function.eval.php)...
Something like this:
$str="\$result=array_merge(";
for($i=1;$i<=$nr;$i++){
$str.="\$sorteios_$i,";
}
$str=substr($str,0,-1);
$str.=");";
eval($str);
Then in $result you have what you need.

Is there a reason you can't recursively merge?
if ($nr > 0) {
$result = $sorteios_1;
for ($i = 2; $i <= $nr; ++$i) {
$result = array_merge($result, ${'sorteios_'.$i});
}
} else {
// you might want to handle this case differently
$result = array();
}

Related

How to store or push array of objects

I need to store service_ids and country_ids in an array in this format
array
[0]["service_id"] should give service id at 0th
index
array[0]["country_id"] should give me country id at 0th index and so on.
function service_ids($conn) {
$ids = array();
$sql = "SELECT id from services";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
array_push($ids, $row["id"]);
}
return $ids;
}
$service_ids = service_ids($conn);
function country_ids($conn) {
$ids = array();
$sql = "SELECT id FROM countries";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
array_push($ids, $row["id"]);
}
return $ids;
}
$country_ids = country_ids($conn);
`//I am having problem here how to store it.
$z = array();
for ($i=0; $i < count($service_ids); $i++) {
$z = array(`
array("service_id"=>$service_ids[$i], "country_id"=>$country_ids[$i])
);
}
print_r($z);
?>
You are basically overwriting array in each iteration in final loop, instead of that store new array in new array index
$z = array();
$counter = 0;
for ($i=0; $i < count($service_ids); $i++) {
$counter = count($z);
$z[$counter]["service_id"] = $service_ids[$i];
$z[$counter]["country_id"] = $country_ids[$i];
}

Running mysql query in loop for each entry in array

I am no programmer and could really use some help in configuring a query below such that it will run for each element in an array and finally add the queried data to the 'mArray'.
Below is two examples of the queries I am running. I have many more of these so it would be much more practical to include all of the ID's in an array and run a foreach loop based on the number of array elements.
$sth = mysqli_query($conn, "SELECT * FROM {$tableName} WHERE ID = 'List1'");
$list1Array = array();
while($r = mysqli_fetch_array($sth)) {
For ($n = 1; $n <= $CI_NOYEARS; $n++){
$list1Array['data'][] = $r[$n];
}
}
$sth = mysqli_query($conn, "SELECT * FROM {$tableName} WHERE ID = 'List2'");
$list2Array = array();
while($r = mysqli_fetch_assoc($sth)) {
For ($n = 1; $n <= $CI_NOYEARS; $n++){
$list2Array['data'][] = $r[$n];
}
}
$mArray = array();
$mArray['list1'] = $list1Array;
$mArray['list2'] = $list2Array;
I have been trying to create this using a simple array and foreach statement as below. However, I just can't seem to make this work. Any help is much appreciated.
$idArray = array(
"List1",
"List2",
);
foreach($idArray as $val) {
$sth = mysqli_query($conn, "SELECT * FROM {$tableName} WHERE ID = $val");
$yearsArray = array(); // Not sure what to do here
while($r = mysqli_fetch_array($sth)) {
For ($n = 1; $n <= $CI_NOYEARS; $n++){
$yearsArray['data'][] = $r[$n]; // Again not sure what to do here
}
}
}

Setting up array key/value pairs and accessing

I have set up an array called $compData by importing data from MySql and pushing two separate arrays called $yearsArray and $salesArray into $compData. Before pushing these two arrays to $compData I have first set their ['name'] to 'Year' and 'Sales', respectively. The code for this is included below.
$sth = mysqli_query($conn, "SELECT * FROM {$tableName} WHERE ID = 'ID_YEAR'");
$yearsArray = array();
$yearsArray['name'] = 'Year';
while($r = mysqli_fetch_array($sth)) {
For ($n = 1; $n <= $CI_YEARS; $n++){
$yearsArray['data'][] = $r["Year$n"];
}
}
$sth = mysqli_query($conn, "SELECT * FROM {$tableName} WHERE ID = 'IS_SALES'");
$salesArray = array();
$salesArray['name'] = 'Sales';
while($rr = mysqli_fetch_assoc($sth)) {
For ($n = 1; $n <= $CI_YEARS; $n++){
$salesArray['data'][] = $rr["Year$n"];
}
}
$compData = array();
array_push($compData,$yearsArray); // 0
array_push($compData,$salesArray); // 1
Now I want to access and echo the data in $compData by using the code below, but this doesn't work. I am not very comfortable with PHP and am wondering if I am not using the ['Year'] and ['Sales'] identifiers correctly. Any help is much appreciated.
foreach($compData['Year'] as $result) {
echo $result, '<br>';
}
foreach($compData['Sales'] as $result) {
echo $result, '<br>';
}
You've set 'Year' as the value of key 'name', but try to use it as key (of another array).
Now you have
echo $compData[0]['name']; // -> 'Year'
echo $compData[1]['name']; // -> 'Sales'
You probably want
$compData = array();
$compData['Year'] = $yearsArray;
$compData['Sales'] = $salesArray;
instead of the array_push..

Array outside while doesn't function

Sorry for the beginner question.
I'm searching about an hour, but I can't understand why my $row outside from the second while doesn't function... The name variable run just the $row var doesn't function...
$i = 0;
while($i < 8)
{
$str = "SELECT * FROM `$name[$i]`";
$result = mysql_query($str, $connessione);
$l = mysql_num_rows($result);
while($l > 1)
{
$strs = "SELECT * FROM `$name[$i]` WHERE `Livello` = '$l'";
$results = mysql_query($strs, $connessione);
$row[$i][$l] = mysql_fetch_array($results);
if I put here the echo I can view the mysql variable
echo $row[$i][$l]['var'];
$l--;
}
if I put here echo $row[$i][$l]['var']; he send me the error " Undefined offset"
$i++;
}
Hope you can help me...
In the place where you put:
echo $row[$i][$l]['var'];
$l value is 0 and you set $row values for $l from 1 to mysql_num_rows($result)
if you put there:
echo $row[$i][1]['var'];
it should work fine assuming mysql_num_rows($result) was more than 1 element.
Probably your code should look like this:
$i = 0;
while($i < 8)
{
$str = "SELECT * FROM `$name[$i]`";
$result = mysql_query($str, $connessione);
$l = mysql_num_rows($result);
while($l > 0) // changed 1 to 0
{
$strs = "SELECT * FROM `$name[$i]` WHERE `Livello` = '$l'";
$results = mysql_query($strs, $connessione);
$row[$i][$l] = mysql_fetch_array($results);
if i put here the echo i can view the mysql variable
echo $row[$i][$l]['var'];
$l--;
}
// added extra loop to display array values
$whileIndex = 0;
while (true) {
if (!isset($row[$i][$whileIndex]['var']) {
break;
}
echo $row[$i][$whileIndex]['var']; // should work
++$whileIndex;
}
$i++;
}
When you try to use echo, $i = 8 and $l = 1. These keys doesn´t exists in your array.

randomly choose one data from blocks of query

I have 100000 records in a table. I need to make a query that reads 10 records and after that 10 more records continuously until the end of the table. For each of the 10 rows groups, I need to pick one random row. Is it possible to accomplish that using a MySQL query? I need some idea to do this. Can anybody help me?
I have tried to do a php loop but it doesn't work.
<?php
include_once ("connection.php");
$data = mysql_query("SELECT * FROM trying");
$result = array();
while ($data2 = mysql_fetch_array($data))
{
array_push($result, array('no'=> $data2['no'],
'source'=> $data2['source'],
'destination'=> $data2['destination']));
}
$e=0;
for ($a = 0; $a <= 49;)
{
for ($i = 0; $i <= 9; $i++,$a++) {
$rand = array();
$rand[$i] = $result[$a];
}
echo json_encode($rand[1]);
}
?>
Insted of this:
for ($a = 0; $a <= 49;)
{
for ($i = 0; $i <= 9; $i++,$a++) {
$rand = array();
$rand[$i] = $result[$a];
}
echo json_encode($rand[1]);
}
you can use this:
$rand = array();
$step = 10;
for ($min = 0; $min <= 49; $min = $min + $step)
{
$max = $min + $step;
$rand[] = $result[rand($min,$max)];
}
echo json_encode($rand);
Since you're echoing a json encoded array, I'm assuming you're calling this php file through an AJAX request, and you want subsequent requests for each 10 rows.
If this is the case, a solution to your problem could be this:
Define limit and offset as vars in your javascript
Pass limit and offset with the AJAX request
If the result of the AJAX request isn't empty, increment offset by limit (offset = offset + limit) to use in the next request
Receive limit and offset in the PHP file (use $_GET or $_POST, depends on the type of request)
Include limit and offset in the MySQL query ("SELECT * FROM trying LIMIT $offset, $limit")
Calculate a random number from 0 to 9 (rand(0, 9))
Fetch the nth (rand) row from the MySQL result (see solution below)
Your PHP file should look like this:
include_once ("connection.php");
$limit = mysql_real_escape_string($_GET['limit']); // If post use $_POST
$offset = mysql_real_escape_string($_GET['offset']); // If post use $_POST
$data = mysql_query("SELECT * FROM trying LIMIT $offset, $limit");
$rand = rand(0, 9);
$count = 0;
while($row= mysql_fetch_array($data)) {
if($rand == $count++) {
echo json_encode($row);
break;
}
}
Put the SQL statement in a loop and use the counter as a variable in the Limit:
$count = mysql_query("SELECT * FROM trying");
$total = round(mysql_num_rows($count) / 10);
for ($i=0;$i<$total;$i++) {
$data = mysql_query("SELECT * FROM trying LIMIT ".($i * 10).", 10");
$result = array();
while ($data2 = mysql_fetch_array($data))
{
array_push($result, array('no'=> $data2['no'],
'source'=> $data2['source'],
'destination'=> $data2['destination']));
}
}
$e=0;
for ($a = 0; $a <= 49;)
{
for ($i = 0; $i <= 9; $i++,$a++) {
$rand = array();
$rand[$i] = $result[$a];
}
echo json_encode($rand[1]);
}
?>
Try with the following:
<?php
include_once ("connection.php");
$query = "SELECT * FROM trying";
$count = 0;
while(true)
{
$data = mysql_query($query." LIMIT ".$count.",10");
$random = rand(1,10);
for($i=1;$i<=$random;$i++)
{
$row = mysql_fetch_array($data);
if($row === false)
{
break 2;
}
}
echo json_encode($row);
$count++;
}
?>
Try this :
<?php
set_time_limit(0);
include_once ("connection.php");
$per = 10;
$start = 0;
$total = 0;
$total_query = mysql_query("SELECT COUNT(*) AS total FROM trying");
if(mysql_num_rows($total_query) == 1) {
$row = mysql_fetch_assoc($total_query);
$total = $row['total'];
$offset = ($start * $per);
$results = array();
while($offset <= $total) {
$tmp = array();
$data_query = mysql_query("SELECT * FROM trying LIMIT ".$offset.",".$per);
while ($row = mysql_fetch_array($data_query)) {
array_push($tmp, array(
'no'=> $row['no'],
'source'=> $row['source'],
'destination'=> $row['destination'])
);
}
array_push($results,$tmp[rand(0,9)]);
unset($tmp);
$start++;
$offset = ($start * $per);
}
echo json_encode($results);
} else {
die("No records found.");
}
?>

Categories