Setting up array key/value pairs and accessing - php

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..

Related

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
}
}
}

Using curly brackets in multidimensional array

I have an array of ID's used to execute mysqli queries in a foreach loop (the below code is just an example - the array will contain more than 50+ elements/ID's). For each array element/ID I query an array which I then include in a compData array. However, I am unsure of how to dynamically define the arrays in the foreach loop. I would very much appreciate if you can check whether I am using ${$val} correctly in the below or if something else is wrong. Thanks.
$idArray = array(
"List1",
"List2",
);
$compData = array();
foreach($idArray as $val) {
$sth = mysqli_query($conn, "SELECT * FROM {$tableName} WHERE ID = {$val}");
${$val} = array();
while($r = mysqli_fetch_array($sth)) {
For ($n = 1; $n <= $CI_NOYEARS; $n++){
${$val}['data'][] = $r[$n];
}
}
$compData[{$val}] = ${$val}
}
foreach($compData['List1'] as $result) {
For ($n = 0; $n <= $CI_NOYEARS; $n++){
echo $result[$n];
}
}
The above code does not work and does not echo any data from the $compData array. Below is an example that works just fine where I execute the code using the ID's directly.
$sth = mysqli_query($conn, "SELECT * FROM {$tableName} WHERE ID = 'List1'");
$List1 = array();
while($r = mysqli_fetch_array($sth)) {
For ($n = 1; $n <= $CI_NOYEARS; $n++){
$List1['data'][] = $r[$n];
}
}
$companyData = array();
$companyData['List1'] = $List1;
foreach($compData['List1'] as $result) {
For ($n = 0; $n <= $CI_NOYEARS; $n++){
echo $result[$n];
}
}
It's a bit tough figuring out what your goal is based on the code you provided, but it seems far more complicated than it needs to be. I think what I've got here will replicate your desired output.
You should also be using prepared statements; they are safer, and take a lot of the overhead out of database queries when you're going to be repeating the same query multiple times. I've implemented them here.
$idArray = ["List1", "List2"];
$sth = $conn->prepare("SELECT * FROM `$tableName` WHERE ID = ?");
foreach($idArray as $val) {
$data = [];
$sth->bind_param("s", $val);
$sth->execute();
$result = $sth->get_result();
while ($r = $result->fetch_array()) {
$data = array_merge($data, array_splice($r, 1, $CI_NOYEARS));
}
$compData[$val]["data"] = $data;
}
foreach($compData["List1"]["data"] as $result) {
echo $result;
}
I don't understand why you're using that curly-brace notation at all when you're just copying it over into a multidimensional compData array anyway? Why not just directly put the data into the array:
for ($n = 1; $n <= $CI_NOYEARS; $n++) {
$compdata[$val]['data'][] = $r[$n];
}
(You'll also need to declare it as an array at the top level of the foreach of course.)
Side note: I would suggest not interpolating data directly into your query string like that, and instead using bound parameters: http://php.net/manual/en/mysqli-stmt.bind-param.php It's much more secure.

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

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();
}

How to format an associative array with another structure?

I have a query like this:
select truck, oil_type, km_min, km_max from trucks;
I'm using codeigniter and with the $query->result_array() function so its loaded in an associative array with this structure:
/*
array(
truck
oil_type
km_min
km_max
)
*/
$arr[0]["truck"] = 2;
$arr[0]["oil_type"] = 2;
$arr[0]["km_min"] = 345;
$arr[0]["km_max"] = 567;
$arr[1]["truck"] = 2;
$arr[1]["oil_type"] = 4;
$arr[1]["km_min"] = 234;
$arr[1]["km_max"] = 867;
$arr[2]["truck"] = 1;
$arr[2]["oil_type"] = 2;
$arr[2]["km_min"] = 545;
$arr[2]["km_max"] = 867;
$arr[3]["truck"] = 4;
$arr[3]["oil_type"] = 3;
$arr[3]["km_min"] = 45;
$arr[3]["km_max"] = 567;
Then, I'm trying to restructure it grouping the trucks by the id, something like this:
/*
trucks - array(
truck
truck_data - array(
oil_type
km_min
km_max
)
)
*/
$arr["truck"][0]= 2;
$arr["truck"][0]["truck_data"][0]["oil_type"] = 2;
$arr["truck"][0]["truck_data"][0]["km_min"] = 345;
$arr["truck"][0]["truck_data"][0]["km_max"] = 567;
$arr["truck"][0]["truck_data"][1]["oil_type"] = 4;
$arr["truck"][0]["truck_data"][1]["km_min"] = 234;
$arr["truck"][0]["truck_data"][1]["km_max"] = 867;
$arr["truck"][1]= 1;
$arr["truck"][1]["truck_data"][0]["oil_type"] = 2;
$arr["truck"][1]["truck_data"][0]["km_min"] = 545;
$arr["truck"][1]["truck_data"][0]["km_max"] = 867;
$arr["truck"][2]= 4;
$arr["truck"][2]["truck_data"][0]["oil_type"] = 3;
$arr["truck"][2]["truck_data"][0]["km_min"] = 45;
$arr["truck"][2]["truck_data"][0]["km_max"] = 567;
I thought in something like the code below:
$res = $query->result_array();
$cnt_total = count($res);
$y = 0;
for ($x=0; $x < $cnt_total -1 ; $x++) {
$truck = $res[$x]["truck"];
$trucks["truck"][$y] = $truck;
$q = $x + 1;
$i = 0;
do{
$trucks[$y][$i]["oil_type"] = $res[$q]["oil_type"];
$trucks[$y][$i]["km_min"] = $res[$q]["km_max"];
$trucks[$y][$i]["km_max"] = $res[$q]["km_max"];
$q++;
$i++;
if ($q <= $cnt_total) break;
} while ( $truck === $res["truck"][$q] );
$y++;
}
But does not work properly... I'm too far of the solution? The performance It's important for me in this particular case.
There is a phpfiddle where you can try:
http://phpfiddle.org/main/code/67j-ui5
Any idea, tip, or advice will be appreciated, and if you need more info, let me know and I'll edit the post.
Try this:
$res = $query->result_array();
$trucks = array();
foreach ($res as $row) {
$truck["truck"] = $row["truck"];
$truck["truck_data"] = array(
'oil_type' => $row["oil_type"],
'km_min' => $row["km_min"],
'km_max' => $row["km_max"],
);
$trucks[] = $truck;
}
var_dump($trucks);
What you've provided as a desired result is a little ambiguous. This might give what you're asking for.
$trucks=array();
$res = $query->result_array(); // assuming this is actually several trucks
foreach ($res as $r){
// set up the array from the data without writing out every column manually
$truck=array(
'truck'=>$r['truck'],
'truck_data'=>$r,
);
// remove the bit you wanted separately as 'truck' from 'truck_data'
unset($truck['truck_data']['truck']);
// push into $trucks
$trucks[]=$truck;
}
Is this what you need? conversion result is stored in $result
$result = array();
foreach($query->result_array() as $truck)
{
$new_truck = array();
$new_truck['truck'] = $truck['truck'];
$new_truck['truck_data'] = array();
$new_truck['truck_data']['oil_type'] = $truck['oil_type'];
$new_truck['truck_data']['km_min'] = $truck['km_min'];
$new_truck['truck_data']['km_max'] = $truck['km_max'];
array_push($result, $new_truck);
}

SQL results to PHP array

I've got the following sql query:
$sql = "SELECT lat, lang
FROM users";
I then use the following code to put the results of the array into two arrays, one for lat and one for lang.
$i = 0;
foreach($results as $row) {
$latArray = array();
$langArray = array();
$latArray[$i] = $row['lat'];
$langArray[$i] = $row['lang'];
$i = ($i + 1);
}
However, it seems that only the last value that is passed to the array is stored. When I echo out each value of the array I get the following error: Undefined offset: 0 which I believe means theres nothing at latArray[0].
I'm sure I've missed something obvious here but why aren't all the values copied to the new array?
$i = 0;
$latArray = array(); //Declare once, do not redeclare in the loop
$langArray = array();
foreach($results as $row) {
$latArray[$i] = $row['lat'];
$langArray[$i] = $row['lang'];
$i = ($i + 1);
}
Declare your array before the loop
$latArray = array();
$langArray = array();
foreach($results as $row) {
$latArray[$i] = $row['lat'];
$langArray[$i] = $row['lang'];
$i = ($i + 1);
}
You should put
$latArray = array();
$langArray = array();
Before foreach cycle (like you do with your counter $i), 'cause with every new value from $result it resets thous values..
so your code will look like:
$i = 0;
$latArray = array();
$langArray = array();
foreach($results as $row) {
$latArray[$i] = $row['lat'];
$langArray[$i] = $row['lang'];
$i = ($i + 1);
}
use fetch_assoc instead:
$latArray = array();
$langArray = array();
while($row = mysql_fetch_assoc($your_query)){
$latArray[$i] = $row['lat'];
$langArray[$i] = $row['lang'];
$i++;
}
if u are using msqli us mysqli_fetch_assoc

Categories