Populating an array with a foreach loop? - php

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

Related

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.

mysql get selection data to store in array but i only get 1 as return

public function select($sql){
$results = $this->connection_database->prepare($sql);
$results->execute();
if($results->rowCount() >0){};
return $results;
}
public function prepare_product(){
if(!empty($this->directoryfile)){
$table = $this->directoryfile;
$sql = "SELECT * FROM $table ";
$results = $this->select($sql);
//Fetch our results into an associative array
$results = $results->fetch(PDO::FETCH_ASSOC);
//The registration date of the stored matching user
$productname = $results['DATA_PATH'];
echo json_encode($productname);
}
}
lets said mysql database have "ID" and "DATA_PATH", my intention is to get all the "DATA_PATH" data store in array , but i only get 1 "DATA_PATH" as return , what did i miss ?
can anyone give me some help ?
the data do return but i only get one , there is 5 item in my database.
You have to:-
1.Create an array variable
2.Apply a loop
3.Assign all data to that array variable
4.At last apply json_encode() to that array variable
like below:-
$results = $this->select($sql);
$productname = array(); // create an array
while($row = $results->fetch(PDO::FETCH_ASSOC)){ // apply loop
//The registration date of the stored matching user
$productname[] = $row['DATA_PATH']; // assign value to that array
}
echo json_encode($productname); // json encode the array variable
You need to fetch ALL data not one. use fetchAll
public function prepare_product(){
if(!empty($this->directoryfile)){
$table = $this->directoryfile;
$sql = "SELECT DATA_PATH FROM $table ";
$results = $this->select($sql);
//The registration date of the stored matching user
$productname = $results->fetchAll(PDO::FETCH_COLUMN, 0);
echo json_encode($productname);
}
}

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

Add data in a multidimensional array dynamically

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

Put result from mysql_query in php array

I want to get some results from the MySQL database and put them in a array like this:
array("value2", "value2", "value3");
I have tried this:
$models = array();
$getmodels = mysql_query("select model from cars");
while($res = mysql_fetch_array($getmodels)) {
$models[$res['model']];
}
This does not work, when i check if the model is in array i get FALSE:
in_array($_REQUEST['model'], $models))
You were supposed to give each key a value, not turning the values into the keys. Try this:
$models = array();
$getmodels = mysql_query("select model from cars");
while($res = mysql_fetch_assoc($getmodels)) {
$models[] = $res['model'];
}
This will create an array with numeric index. Each key will have the car's model as the value.

Categories