Undefined index from a foreach() loop [duplicate] - php

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 8 years ago.
ItemDb class
public function getRandomItem() {
$query = "SELECT * FROM `items` ORDER BY RAND() LIMIT 2";
return $this->query($query);
}
Index.php
$item = new Item();
$result = $item->getRandomItem();
while ($row = $result->fetch_assoc()) {
foreach ($row as $key => $value) {
//I want to put them in a array but the two items need to be separated
}
}
I get two different items out of the database how can I split them and put them in one array separated like:
$array[$key][$value]
Sorry for my English its my second language and I hope you guys understand me.

You need to declare $itemArray[$key] before you use it. So your code needs to look like
$itemArray = array();
while ($row = $result->fetch_assoc()) {
foreach ($row as $key => $value) {
if(!isset($itemArray[$key])) {
$itemArray[$key] = array(); //Declare it
}
$itemArray[$key][] = $value;
}
}

Related

how to get variables from column names [duplicate]

This question already has answers here:
variable variables
(5 answers)
Closed 1 year ago.
how to get variables from column names
$sq = "select * from arts where id = :aid limit 1";
$st = $db->prepare($sq);
$st->execute([":aid" => $id]);
$row = $st->fetch();
now, instead of:
$cat = $row['cat'];
$title = $row['title'];
$subtitle = $row['subtitle'];
... so on
I need something like:
foreach($column_name as $el){
$var_name = $el;
}
There's rarely a good reason to do this, just use the array. However, you can use variable variables from the keys if there is only one row as you show:
foreach($row as $key => $val){
$$key = $val;
}
There is also extract() but may be even worse practice.

Remove duplicates from array inside another array [duplicate]

This question already has answers here:
php multi-dimensional array remove duplicate [duplicate]
(6 answers)
Closed 3 years ago.
I have an array who have another one inside, but when i get the response from database i have duplicates, and i don't want to have this, any help?
I have used the solution provided in the link and it doesn't work
"Warning: Illegal offset type in"
$atividadesArray = array();
foreach ($result as $row) {
$idAtividade = $row['idAtividade'];
if (!isset($atividadesArray[$idAtividade])) {
$atividadesArray[$idAtividade]['idAtividade'] = $row['idAtividade'];
$atividadesArray[$idAtividade]['Periodo'] = $row['Periodo'];
$atividadesArray[$idAtividade]['Mes'] = $row['Mes'];
$atividadesArray[$idAtividade]['haveClasses'] = $row['haveClasses'];
$atividadesArray[$idAtividade]['Destinatarios'] = $row['Destinatarios'];
$atividadesArray[$idAtividade]['Nome'] = array();
$atividadesArray[$idAtividade]['Grupo'] = array();
$atividadesArray[$idAtividade]['Departamento'] = array();
}
$atividadesArray[$idAtividade]['Nome'][] = $row['Nome'];
$atividadesArray[$idAtividade]['Grupo'][] = $row['Grupo'];
$atividadesArray[$idAtividade]['Departamento'][] = $row['Departamento'];
}
foreach ($atividadesArray as $idAtividade => $t ) {
$json[]=$t;
}
echo json_encode($json);
Just do not add the item, if it already exists in the array:
...
// Search for the element in the array
if (array_search($row['Departamento'], $atividadesArray[$idAtividade]['Departamento']) === false) {
// Add only if nothing found
$atividadesArray[$idAtividade]['Departamento'][] = $row['Departamento'];
}
Note === operator is required to not mess element with key 0 (the first added) and false boolean value;

SQL select as a PHP function [duplicate]

This question already has answers here:
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in
(3 answers)
Closed 7 years ago.
I'm selecting data from MySQL. My code looks like this:
$sql = "SELECT oznacenie_odpadu FROM zdroj_dat ORDER by ID ASC";
if ($result = $conn->query($sql)) {
// fetch associative array
while($row = $result->fetch_assoc()) {
echo '<option value="'.$row['oznacenie_odpadu'].'" >'.$row['oznacenie_odpadu'].'</option>';
}
}
This part of code is in my code multiple times. I'm calling it 5times only string "oznacenie_odpadu" is changing. Therefore I made function:
function select($data) {
$sql = "SELECT rozmer FROM zdroj_dat ORDER by id ASC";
if ($result = $conn->query($sql)) {
// fetch associative array
while($row = $result->fetch_assoc()) {
echo '<option value="'.$row[$data].'" >'.$row[$data].'</option>';
}
}
}
Calling it with select("somevalue");
Syntax is ok because I didn't change anything but when I load the page the data from database are not retrieved.
You have a variable scope issue. $conn is not available inside of your function. You need to pass it as a parameter so ic an be used inside of your function.
function select($conn, $data) {
$sql = "SELECT rozmer FROM zdroj_dat ORDER by id ASC";
if ($result = $conn->query($sql)) {
// fetch associative array
while($row = $result->fetch_assoc()) {
echo '<option value="'.$row[$data].'" >'.$row[$data].'</option>';
}
}
}
Call it:
select($conn, "somevalue");

Create an array from values from mysql table [duplicate]

This question already has answers here:
Creating an array from a MySQL table
(2 answers)
Closed 10 years ago.
I am using PHPlot to make a graph.
I have an issue in generating the array from a MySQL table.
Basivally, I want to array is as follows:
$values = array($arrayx);
array('a',-3),
array('b',5),
array('c',7),
array('d',8),
array('e',12),
array('f',-6),
//);
$graph->SetDataValues($values);
$graph->SetXTickPos('none');
$graph->SetXTickLabelPos('none');
Part of the code where I tried to retrieve values from table to feed the array
$query="SELECT * FROM tasks";
$result=mysql_query($query);
//using a for loop to add values to the array
while ($resource=mysql_fetch_array($result)){
$thedate = $resource["date"];
$title = $resource2["title"];
$innerarray = "array('.$thedate.', $title),";
}
$values = array($innerarray).");";
$graph->SetDataValues($values);
$graph->SetXTickPos('none');
$graph->SetXTickLabelPos('none');
//Draw it
$graph->DrawGraph();
}
The way I'm doing the $innerarray and $values seems wrong. Can you please help me fix it?
Thank you
try replacing
$innerarray = "array('.$thedate.', $title),";
with
$innerarray = array($thedate, $title);
$new = array();
while(for condition ){
$new[] = '\''.thedate[$i].''\','.$title[$i].'\';
}
var_dump($new);
this an idea, you need to edit the code to make it working
I assume it is this that you want:
$sql="SELECT datefield, titlefield FROM tasks";
....
while (list($thedate,$thetitle) = mysql_fetch_array($result)) {
$values[] = array($thedate,$thetitle);
}
echo $values[0][0]; // will output your 1st date
echo $values[0][1]; // will output your 1st title

Can I convert individual fields of a 'mysql_query' to arrays? [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 1 year ago.
Likely a remedial question, but in all my days as a PHP user I have yet to encounter an answer. Basically, is there any way to grab a single field of a "mysql_query" as an array? For instance say I have the following:
$query = "Select id,first_name,last_name FROM people";
$result = mysql_query($query);
Is there any way to grab each (id, first_name, last_name) as individual arrays without iterating through the recordset? Can I say something like:
$ids = field_to_array($result['id']);
$first_names = field_to_array($result['first_name']);
$last_names = field_to_array($result['last_name']);
As I said, in the past I've always simply built the arrays as needed, but an existing method would be handy.
mysql doesn't have that as a native function. you could always write your own..
function mysql_convert_cols($dataset) {
foreach ($dataset as $row => $values) {
foreach ($values as $column => $value) {
$return[$$column][$row] = $value;
}
}
return($return);
}
$resultConverted = mysql_convert_cols($result);
$id=$resultConverted['id'];
$firstName=$resultConverted['firstName'];
I'm not sure why do you need this , but you can do it like this :
$resultArray = array();
while($row = mysql_fetch_array($result)){
$resultArray[] = array(
"id" => $row['id'],
"firstName"=>$row['first_name'],
"lastName"=>$row['last_name']
);
}
Check if values are in :
print_r($resultArray);
Then you can foreach or to do the for loop on values.

Categories