Add data in a multidimensional array dynamically - php

I am needing to add data dynamically into a multidimensional array. The data comes from a query in the database. I can see through the "echo" all elements, but in time to add to the multidimensional vector data and overwrite only the last record is added.
My example below:
$queryu = "SELECT * FROM usuario ORDER BY id";
$stmtu = $con->prepare($queryu);
$stmtu->execute();
$numu = $stmtu->rowCount();
$j = 0;
$lista;
if ($numu > 0) {
$colunas = 3;
while ($rowu = $stmtu->fetch(PDO :: FETCH_ASSOC)) {
extract($rowu);
$lista['id'] = $id;
$lista['nome'] = $nome;
$j++;
}
}
The result:
id - 6
nome - teste
This is the last record added.
Thanks!!!

You don't create a multi dimensional array by now. You just update create two key => value pairs id and nome. If you want to store multiple of them you have to create a multidimensional array which means an array inside another array:
$lista = array(); // init your array!
while ($rowu = $stmtu->fetch(PDO :: FETCH_ASSOC)) {
extract($rowu);
$lista[] = array(
'id' => $id,
'nome' => $nome
);
$j++;
}
Or do it even smarter (if the keys in the final array are the same as the column names):
$lista = array(); // init your array!
while ($rowu = $stmtu->fetch(PDO :: FETCH_ASSOC)) {
$lista[] = $rowu;
$j++;
}

Modify your code as follows
$queryu = "SELECT * FROM usuario ORDER BY id";
$stmtu = $con->prepare($queryu);
$stmtu->execute();
$numu = $stmtu->rowCount();
$lista = array();
if ($numu > 0) {
$colunas = 3;
while ($rowu = $stmtu->fetch(PDO :: FETCH_ASSOC)) {
extract($rowu);
$lista[] = array('id' => $id, 'nome' => $nome);
}
}
As you probably noticed here, I've removed j index (you don't need it; I suppose that you would use it as "first-level-index" of your multidimensional array) and added that statement: $lista[] =. "Magic" happens just there: with this command ($arrayname[] =) you can append to existent array a new element.
However I don't know from where you're obtaining $id and $nome so this snippet could fail due to undefined variables and similar

Related

Is this the correct PHP Syntax for adding an associative array to an existing associative array.

I have three variables retrieved from a database and I would like the first variable to be the key for the second variable and for that second variable to be the key for the third variable. In essence a two-dimensional array.
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$unit_id = $row['id'];
$unit_code = $row['unit_name'];
$unit_description = $row['unit_description'];
$units = [$unit_id => $unit_code];
$units += [$unit_code => $unit_description];
}
return $units;
You can simply make like this
<?php
$unit_id = 'id';
$unit_code = 'unit_name';
$unit_description = 'unit_description';
$units[$unit_id] = [$unit_code=>$unit_description];
//$units[$unit_id][$unit_code] = $unit_description;
print_r($units);
?>
Live demo : https://eval.in/880865
Yess you can do this.
$array = [
'data' => 'my data'
];
now you can do this simply
$array['anotherArray'] = $anotherArray;
If "id", "unit_name" and "unit_description" are respectively the first, second and third value of the database, this is the code:
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$units[$row['id']][$row['unit_name']] = $row['unit_description'];
}
return $units;
If array consists of key, value parts (associative arrays), which your case is like that, you just need to:
$data[$key] = $value;
So in your case it would be:
$units[$unit_code] = $unit_description;
If your arrays' keys are indexed, then using array_push can do the job too:
array_push($units, $unit_description);

Populating an array with a foreach loop?

I'm trying to populate the array for the variable $example_data. I have an array of Mass' and dates that I want to populate this array with. However I do not know how to create a new array entry for each $mass[$x] and $date[$x] that I want to store. I've tried putting a foreach loop inside the $example_data = array( but it didnt work.
This is what I want it to do, but doesn't work:
$example_data = array(
foreach($exer->results() as $ex){
$mass = $ex->Mass;
$date = $ex->Date;
array($date,$mass),
);
This is what I've tried but not sure how to complete it:
$userID = $user->data()->id;
$sql = "SELECT * FROM userdetails WHERE UserID = ".$userID."";
$details = DB::getinstance()->query($sql);
$x = 1;
foreach($details->results() as $detail){
/** getting data from each record from field Mass and storing it in $mass array **/
$mass[$x] = $detail->Mass;
$date[$x] = $detail->Date;
$x++;
}
$x = 1;
$example_data = array(
array($date[$x],$mass[$x]),
/** I want it to create a new array entry for each $mass[] **/
);
It depends on the type of database you're using...
For example if you're using MySQL, it's mysqli_fetch_assoc()
You're trying to fetch a result set into an associative array but the result set itself is an associative array
try...
$sql = "SELECT * FROM userdetails WHERE UserID = ".$userID."";
$details = DB::getinstance()->query($sql);
$example_data = array(
array("Mass"),
array("Date")
);
while($row = $details->fetch_assoc()) {
array_push($example_data['Mass'], $row['name_of_mass_column_in_db']);
array_push($example_data['Date'], $row['name_of_date_column_in_db']);
}
}
Basically, you can just fetch an associative array instead of populating an associative array with an associative array...

How to extract value from foreach loop by json_encode

I have php result set, and from these result i am extracting value using php foreach loop. I put the foreach loop value in array $summery[]. but when i try to print value its print value at once. but i need separate value/result set for each foreach loop as json code so that i can print each result separately. My foreach loop following :
foreach($result_UserWrSet as $UserWrInfo) {
$summery[]=$UserWrInfo['wr_id'];
$summery[]=$UserWrInfo['wr_number'];
$summery[]=$UserWrInfo['wr_title'];
$dateFlag=1;
$result_StartDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
$result_EndDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
$summery[]=$result_StartDate;
$sql_GetUserName = "SELECT user_name FROM user_information where user_id='$UserWrInfo[user_id]'";
$result_GetUserName = mysqli_query($conn, $sql_GetUserName);
$num_GetUserName = mysqli_num_rows($result_GetUserName);
if ($num_GetUserName > 0){
$UserNameByIdRos = $result_GetUserName->fetch_assoc();
$UserNameById=$UserNameByIdRos['user_name'];
}
else {$UserNameById=NULL;}
$summery[]=$UserNameById;
$result_CurrentHop = $WrDates ->getCurrentHopByWrId($UserWrInfo['wr_id']);
$result_CurrentHopName = $WrDates ->GetHopsNameById($result_CurrentHop);
$summery[]=$result_CurrentHopName;
$result_EndDate = $WrDates ->completedDate($UserWrInfo['wr_id']);
$summery[]=$result_EndDate;
}
print json_encode($summery);
My result become
["69","010116-69","Wr test","01\/01\/16 18:45 PM","planner","Done","01\/01\/16 19:16 PM","68","010116-","This is title","01\/01\/16 18:44 PM","planner","Done"]
but i need :
[["69","010116-69","Wr test","01\/01\/16 18:45 PM","planner","Done"],["01\/01\/16 19:16 PM","68","010116-","This is title","01\/01\/16 18:44 PM","planner","Done"]]
Use this code, you need to use another array in which all the sub array's to be pushed and encode that array after pushing all the items into it
<?php
$dataArray = array(); /// empty array in which sub array's to be pushed..
foreach($result_UserWrSet as $UserWrInfo) {
$summery= array();
$summery[]=$UserWrInfo['wr_id'];
$summery[]=$UserWrInfo['wr_number'];
$summery[]=$UserWrInfo['wr_title'];
$dateFlag=1;
$result_StartDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
$result_EndDate = $WrDates ->getDateById($UserWrInfo['date_id'],$dateFlag);
$summery[]=$result_StartDate;
$sql_GetUserName = "SELECT user_name FROM user_information where user_id='$UserWrInfo[user_id]'";
$result_GetUserName = mysqli_query($conn, $sql_GetUserName);
$num_GetUserName = mysqli_num_rows($result_GetUserName);
if ($num_GetUserName > 0){
$UserNameByIdRos = $result_GetUserName->fetch_assoc();
$UserNameById=$UserNameByIdRos['user_name'];
}
else {$UserNameById=NULL;}
$summery[]=$UserNameById;
$result_CurrentHop = $WrDates ->getCurrentHopByWrId($UserWrInfo['wr_id']);
$result_CurrentHopName = $WrDates ->GetHopsNameById($result_CurrentHop);
$summery[]=$result_CurrentHopName;
$result_EndDate = $WrDates ->completedDate($UserWrInfo['wr_id']);
$summery[]=$result_EndDate;
////Push sub array i.e summary into the main array...
$dataArray[] = $summery;
}
print json_encode($dataArray);
?>
You need a multidimensional array, you can follow below code:
$result_UserWrSet = array(
'0' => array('wr_id'=>'12','wr_number' =>'785', 'wr_title' => 'title1'),
'1' => array('wr_id'=>'12','wr_number' =>'785', 'wr_title' => 'title1'));
foreach($result_UserWrSet as $key => $UserWrInfo) {
$summery[$key][]=$UserWrInfo['wr_id'];
$summery[$key][]=$UserWrInfo['wr_number'];
$summery[$key][]=$UserWrInfo['wr_title'];
}
print json_encode($summery);
output: [["12","785","title1"],["12","785","title1"]]
Good Luck :)
Currently, you are just adding new items to a one dimensional array. You need to create a separate array per result, like this:
foreach($result_UserWrSet as $UserWrInfo) {
$item = array();
// Change all $summary in the loop to: $item, like this:
$item[]=$UserWrInfo['wr_id'];
$item[]=$UserWrInfo['wr_number'];
$item[]=$UserWrInfo['wr_title'];
//...and so on
// Then add this last in your loop:
$summary[] = $item;
}
This will create one array per iteration that is put in the main array, which then becomes a multi dimensional array.

adding values to php multidimensional associative array

Hi in the code below I want to add an extra value for the associative array. For each queryresult in wich elements ["Nietaanwezig"] and ["Aanwezig_diner"] both are 0 I want to add the element ["Nietingevuld"] and set it's value to 1, otherwise i want to add the element ["Nietingevuld"] and set it's value to 0. Albeit I have tried a lot of options, I don't seem to ge a good solution.
// numerically indexed array of places
$namen = [];
$queryresult = [];
// TODO: search database for places matching $_GET["geo"]
$search = $_GET["zoekopdracht"];
if ($search = "diner")
{
$namen = query ("SELECT * FROM gasten WHERE Typegast = 1");
foreach ($namen as $naam)
{
$queryresult [] = [
"Voornaam" => $naam["Voornaam"],
"Achternaam" => $naam["Achternaam"],
"Nietaanwezig" => $naam["Nietaanwezig"],
"Aanwezig_diner" => $naam["Aanwezig_Diner"],
];
}
Don't do it all in a single stage then. Build the new child array, modify it as necessary, THEN insert it into the parent array:
$temp = array('Voornaam' => $naam['Voornaam'], etc....);
if (whatever you want to check) {
$temp['something'] = 'else';
}
$queryresult[] = $temp;

Add element and key to array php

I'm trying to add an element to array, but I get a weird output. The code is the following:
$getalltokens = $db->query("SELECT * FROM Tables WHERE available = '$comp'");
while ($row = $getalltokens->fetch(PDO::FETCH_ASSOC))
{
$fid = $row['FID'];
$tok = $row['token'];
$sql = $db->query("SELECT Firstname,Lastname FROM Users WHERE Token = '$tok'");
$rez = $sql->fetch(PDO::FETCH_ASSOC);
$names[] = $rez;
$fidzy = array(
'FID' => $fid
);
array_push($names, $fidzy);
}
$getalltokens = $db->query("SELECT FID FROM Tables WHERE available = '$comp'");
$tokenz = $getalltokens->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($names);
And the output I get is:
[{"Firstname":"Test","Lastname":"Test"},{"FID":"5"},
{"Firstname":"Test2","Lastname":"Test2"},{"FID":"4"}]
While what I need is the FID to be inside the $names array, so it would be more like:
[{"Firstname":"Test","Lastname":"Test","FID":"5"}]
$rez['FID'] = $fid; /* Added */
$names[] = $rez;
/* $fidzy and array_push removed */
You can use instead of array_push() like
$arrayname[indexname] = $value;
if you use array_push()
<?php
$array[] = $var;
?>
Note: If you use `array_push()` to add one element to the array it's
better to use$array[] = because in that way there is no overhead of
calling a function.
Note: `array_push()` will raise a warning if the first argument is not an array. This differs from the `$var[]` behavior where a new array
is created.
Reference Array push
The solution to the specific problem at hand is selecting all the necessary data in a single query, removing the need to add elements to any array. This is done in the following fashion:
$sql = $db->query("SELECT
Users.Firstname,Users.Lastname,Tables.FID
FROM Users,Tables
WHERE Users.Token = Tables.token");
$rez = $sql->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rez);

Categories