i want to build an object (for angular) so it will look like so
user:{
{education:
{high school:'some school'},
{faculty:'faculty of science'}
},
{skills:
{skill1:'sk1'},
{skill2:'sk2'}
}
}
and this is my php and mysql query:
$testArr = array();
$user = new stdClass();
$params = DB::select( DB::raw("SELECT param.*, sys_param_values.*,param_value.*,type_user.*,
param.name AS paramName,
doc_param.name AS docParamName
FROM param
LEFT JOIN doc_param ON param.doc_param_id = doc_param.id
LEFT JOIN sys_param_values ON param.id = sys_param_values.param_id
LEFT JOIN param_value ON sys_param_values.value_ref = param_value.id
LEFT JOIN type_user ON sys_param_values.ref_user_id = type_user.id"));
query result:
"params":[{"id":21,"name":"faculty","type_id":5,"doc_param_id":14,"created_at":"2015-05-17 14:13:12","updated_at":"2015-06-04 08:19:43","doc_type":12,"ref_user_id":21,"param_id":48,"iteration":null,"value_short":null,"value_long":null,"value_ref":74,"value":"some High","type":"tech-admin","email":"xxxxxxx8#gmail.com","password":"$2y$10$6L8voJ3DgZuADHZLaBh4jei\/U.svVdcN4B02XFc9mF\/p8m5RpfJtG","password_new":null,"first_name":"jon","last_name":"snow","street_1":"shiv","street_2":"tey","city":"123456","state":"aa","zipcode":"47252","country":"usa","phone_1":"123456","phone_2":"123456","mobile":"123456789","date_of_birth":"2015-05-18 11:25:42","registration":"0000-00-00 00:00:00","last_login":"2015-05-20 09:14:52","send_newsletters":1,"send_notifications":1,"remember_token":"dtlimLNZBWdCxcqKR7NdDblMiafkZOxywN4jjUac53v7NI4e1t6eokJXdsoy","paramName":"faculty","docParamName":"education"}
after the query witch is good, i loop :
foreach($params as $k=>$v) {
$paramName = $v->paramName;
$value = $v->value;
$testArr[$v->docParamName] = array();
$testArr[$v->docParamName][$paramName] = $v->value;
}
and the result is :
"test":{
"education":
{"high_school":"some High"},
"skills":
{"skill_1":"skill_1 Value"},
"experience":
{"xp_1":"xp1 value"}
}
the thing is i have more if these parameters for example "skill_2" and "skill_3" that are suppose to go in the "skills" object.
but this loop anly gets the last parameter..
where am i suppose to specify a key or something so that all of the skills go to the skills object and so on..
You need to define like this:-
foreach($params as $k=>$v) {
$paramName = $v->paramName;
$value = $v->value;
// $testArr[$v->docParamName] = array(); // comment the line
$testArr[$v->docParamName][$paramName] = $v->value;
}
Note:- the line is commented because you already defined $testArr as an array before foreach loop.thanks
You are re-initializing your sub-object on each iteration:
$testArr[$v->docParamName] = array(); // <- By this, you remove all previously
// assigned values
$testArr[$v->docParamName][$paramName] = $v->value;
Initializing an array before appending elements to it is a good idea, because it will otherwise trigger a warning when you try to append to a non-initialized array. But you should only initialize the array if it was not initialized before:
if (!array_key_exists($v->docParamName, $testArr)) {
$testArr[$v->docParamName] = array();
}
$testArr[$v->docParamName][$paramName] = $v->value;
Related
I have a sql request to do with a php array to find all the occurrences of a search bar.
I can't get this done. This is my code :
$texte = $_POST['texte'];
$texte = explode(" ", $texte);
$query_parts = array();
//Proximité
foreach ($texte as $value) {
$value = "%".$value."%";
}
$sql = "SELECT * FROM PROXIMITE WHERE titrefr LIKE ':texte'";
$req = $bd->requete_obj($sql, array('texte'=>$texte));
while($select = $req->fetch()){
error_log('Test');
}
Your foreach-loop does not actually modify the variables, because they are passed by Value - meaning a copy.
to modify them, you have to pass them by reference:
foreach ($texte as &$value) {
$value = "%".$value."%";
}
that way, the actual values in your array are being manipulated.
secondly: you can not give your database an array as parameter. instead, you could loop through the array. if you implement that in your first loop, you don't even have to use references anymore:
$sql = "SELECT * FROM PROXIMITE WHERE titrefr LIKE :texte";
foreach ($texte as $value) {
$value = "%".$value."%";
$req = $bd->requete_obj($sql, array('texte'=>$value));
while($select = $req->fetch()){
error_log('Test');
}
}
Probably a stupid question here, I apologize...
I have a SQL request into a foreach, like below.
The "auth" string is correctly defined, a "echo $auth" returns what I want. But the sql request returns nothing.
// $auth=something;
$val=array(value1,value2,value3);
foreach ($val as $j)
{
$req = mysqli_fetch_array(mysqli_query($link,"select val from user where auth='$auth'"));
$$j=$req[val];
}
My goal is to select the sql fieds contained in the $val array (it perfectly works in others parts of my project). Thanks in advance.
I also tried this, still does not return anything :
$val = array('mail','preferences','info','langue'); // This must be an array
$fields = explode(",", $val);
$req = mysqli_fetch_array(mysqli_query($link,"select $fields from user where auth='$auth'"));
$mail = $req[0]; $preferences = $req[1]; $info = $req[2]; $info = $req[3];
My goal is to select the sql fieds contained in the $val array
So the $val contains the fields you want to use on your query. You can use an explode() to retrieve all the fields without a foreach:
$fields = explode(",", $val);
$req = mysqli_fetch_array(mysqli_query($link,"select $fields from user where auth='$auth'"));
And the you can get the value:
$value1 = $req[$val[0]]; // First field
Okay, let's resume all that. so we have two methods. First :
$val=array(mail,preferences,info,langue);
foreach ($val as $j)
{
$auth = $_SESSION['auth'];
echo $auth; //this works
$req = "select val from user where auth='$auth'";//this works only in phpMyadmin
$req = mysqli_fetch_array(mysqli_query($link,$req));
$$j=$req[val];
}
echo $mail; //gives nothing of course...
And here's the second one :
val = array('mail','preferences','info','langue');
$fields = explode(",", $val);
$req = mysqli_fetch_array(mysqli_query($link,"select $fields from user where auth='$auth'"));
$mail = $req[$val[0]]; $preferences = $req[$val[1]]; $info = $req[$val[2]]; $info = $req[$val[3]];
Still nothing works. No php problem detected, my Mysqli instances work correctly... PLEASE do notice we are in debug mode, so my first code is not optimized of course...
The problem is the use of explode which splits a string on a delimiter and create an array. You already have an array, but you want to make it a string. To do this you can use implode:
$columns = array("mail", "preferences", "info", "language");
$sql = sprintf("SELECT %s FROM user WHERE auth='%s'", implode(",", $columns), $auth);
$query = mysqli_query($sql); //..fetch possible errors
$row = mysqli_fetch_array($query); //..make sure a row was returned
list($mail, $preferences, $info, $language) = $row;
echo $mail;
Im very new to PHP coding.
Just im getting values from object (class Project)and im iterating all object items to calculate duration of each project.
$projectDet = new Project();
$projectList = $projectDet->Find("name = ?",array($requ['name'] ));
if($projectList==false)
return 0;
foreach($projectList as $proj)
{
$reportData = array();
$reportData[] = array("Project","TotalTime"); //Testing
$key = $proj->id;
$EstDUR[$key] = (strtotime($proj->Enddt) - strtotime($proj->Startdt));
}
return $reportData;
But reportData returns null even projectList is not null.
Initate $reportData before foreach:
$reportData = array()
foreach($projectList as $proj) {
(..)
Hey guys I have a little issue with a function that retrieves data from a MySQL Database and then I iterate over the results with a foreach loop, checking a value to see if it is null and if it is, replacing it with another value.
The problem with this function is this, that after returning the data I'm only able to view one record retrieved from the database. Probably something simple but it's beyond me.
I would like to do this before passing it to the controller or view. Maybe this isn't possible with the foreach loop? What am I missing?
Here is an example of my code.
public function get_basic_user_data(){
$sql = 'SELECT Account.First_Name, Account.Last_Name, Account.User_Name, Profile_Photos.Thumb_Url
FROM Account
LEFT JOIN Profile_Photos ON Account.idAccount = Profile_Photos.Account_Id
AND Profile_Photos.Active = 1
WHERE Account.idAccount != ?';
$account_id = $this->get_account_id();
$data = $this->db->query($sql, $account_id);
foreach($data->result() as $row){
if($row->Thumb_Url == NULL){
$image = base_url().'assets/images/no_photo_thumb.png';
}else{
$image = $row->Thumb_Url;
}
$new_data = new stdClass;
$new_data->First_Name = $row->First_Name;
$new_data->Last_Name = $row->Last_Name;
$new_data->User_Name = $row->User_Name;
$new_data->Thumb_Url = $image;
}
return $new_data;
}
Hopefully someone can help me with this? Thanks!
At the moment you are just returning the last data row. Change your code like this to return an array of all your rows from that function:
$rows = array()
foreach($data->result() as $row){
if($row->Thumb_Url == NULL){
$image = base_url().'assets/images/no_photo_thumb.png';
}else{
$image = $row->Thumb_Url;
}
$new_data = new stdClass;
$new_data->First_Name = $row->First_Name;
$new_data->Last_Name = $row->Last_Name;
$new_data->User_Name = $row->User_Name;
$new_data->Thumb_Url = $image;
$rows[] = $new_data;
}
return $rows;
This way every row returned from the database will be added to an array named $rows. At the end you have to return your new array.
You are overwriting $new_data each iteration. Try this
$new_data = new stdClass
...
$all_data[] = $new_data;
Instead of checking for null value in the code, you could just use a IFNULL statement in the SQL query, this does separate the logic a bit but it might just be worth it in this case.
The function returns only the last row in the result because the new_data variable is overwritten in every step of your loop. Declare new_data an array at the start of your function and add rows as array elements
...
$new_data[] = new stdClass;
...
Each iteration of the foreach overwrites $new_data so in the end when the function returns, only the last fetched row will be returned. To return more than one row you could store all the rows in an array and then return the array in the end. It would look something like this:
public function get_basic_user_data(){
$sql = 'SELECT Account.First_Name, Account.Last_Name, Account.User_Name, Profile_Photos.Thumb_Url
FROM Account
LEFT JOIN Profile_Photos ON Account.idAccount = Profile_Photos.Account_Id
AND Profile_Photos.Active = 1
WHERE Account.idAccount != ?';
$account_id = $this->get_account_id();
$data = $this->db->query($sql, $account_id);
$data = array();
foreach($data->result() as $row){
if($row->Thumb_Url == NULL){
$image = base_url().'assets/images/no_photo_thumb.png';
}else{
$image = $row->Thumb_Url;
}
$new_data = new stdClass;
$new_data->First_Name = $row->First_Name;
$new_data->Last_Name = $row->Last_Name;
$new_data->User_Name = $row->User_Name;
$new_data->Thumb_Url = $image;
$data[] = $new_data;
}
return $data;
}
To be able to use this function you have to change the code that uses it to loop through the array of objects.
Why will my array have different output within the while loop, like it fetch all data from database in json, but once I declare the array outside of the while loop as commented out it gives output single row in json? Am I missing something basic or what? Thanks in advance
$query = "SELECT * from creative ORDER BY rand()";
$rs = mysql_query($query);
//$arr = array();
while ($obj = mysqli_fetch_object($rs)) {
$arr[] = $obj;
$cid = $arr -> id; //get id
}
if (isset($imei) && !empty($imei)) {
$add = array('delay'=>"1800000"); //Add Objects to JSON Encoded Array
$arr[] = $add;
echo json_encode($arr);
Have you tried array push?
$arr = array();
while ($obj = mysqli_fetch_object($rs)) {
//$arr[] = $obj;
array_push($arr, $obj);
//$cid = $arr -> id; //get id
}