I have 50 variables in php. I want to check each of them and if they true then add 2 points in a variable called $point. I am new so I write a few lines but I think I am doing wrong way.
$strenght_point = 0;
if($f_name){$strenght_point++;}
if($l_name){$strenght_point + 2;}
if($full_name){$strenght_point + 2;}
How can I do it right way.Thanks
Update my full function is here...
It's Codeigniter Controller Function
Hope you guys understand well now
function strength_scale() {
$user_id = $this->uri->segment(2);
$user_name = $this->uri->segment(3);
$query = $this->db->get_where('aoa_user', array('id' => $user_id, 'username' => $user_name));
foreach ($query->result() as $row){
$f_name = $row->f_name;
$l_name = $row->l_name;
$full_name = $row->full_name;
$username = $row->username;
$alias_name = $row->alias_name;
$gender = $row->gender;
$country = $row->country;
$avatar = $row->avatar;
$cover_photo = $row->cover_photo;
$email = $row->email;
$skill = $row->skill;
$other_skills = $row->other_skills;
$ex_time = $row->ex_time;
$about = $row->about;
$company = $row->company;
$company_position = $row->company_position;
$phone = $row->phone;
$facebook = $row->facebook;
$facebook_page = $row->facebook_page;
$google_plus = $row->google_plus;
$twitter = $row->twitter;
$youtube = $row->youtube;
$skype = $row->skype;
$linkedin = $row->linkedin;
$website = $row->website;
$latitude = $row->latitude;
$longitude = $row->longitude;
$verification = $row->verification;
}
$strength_point = 0;
if($f_name){$strength_point++;}
if($l_name){$strength_point + 2;}
if($full_name){$strength_point + 2;}
}
Create an array with the variables instead.
https://3v4l.org/FYTtG
$arr = array("f_name" => true, "l_name" => true, "full_name" => true);
$strength=0;
Foreach($arr as $var){
if($var) $strength = $strength+2;
}
Echo $strength;
As Rizier123 said, you need to increment your strength variable correcly.
You could write a simple function that would accept one of your 50 variables and return the strength increment:
function defineStrength($param)
{
if ($param) {
return 2;
}
return 0;
}
$strength = 0;
$f_name = true;
$l_name = false;
$full_name = false;
$strength += defineStrength($f_name);
$strength += defineStrength($l_name);
$strength += defineStrength($full_name);
However, an array would be a better way to go, as Andreas mentionned.
In your question update you said you use CodeIgniter. As the documentation states you can return the query result as a pure array.
So you could further develop like that :
function defineStrengthFromArray(array $row)
{
$strength = 0;
foreach ($row as $param) {
$strength += defineStrength($param);
}
return $strength;
}
foreach ($query->result_array() as $row){
$strength = defineStrengthFromArray($row);
}
Related
In my wordpress functions file, I'm getting sql query results of only post IDs, then taking those IDs to create an array that I send to my page.
This works perfectly but I want to re-order it based on one of the values I generate in the array process. I have a value of 'featured' and I want to make it so that any results where featured = 1 are first in the array.
$myresults = $wpdb->get_results( $sqlStatement );
$ress = array();
$cnt = 0;
$imgpath = '';
if(count($myresults)>0){
foreach ($myresults as $key => $value) {
$id = $value->ID;
if(get_post_meta($id,'_awpcp_extra_field[36]',true) !='' && get_post_meta($id,'_awpcp_extra_field[37]',true) != ''){
$ress[$cnt]['featured'] = get_post_meta($id,'_awpcp_is_featured',true);
$imgpath = get_the_post_thumbnail_url($id,'dailymag-featured');
if($imgpath){
$ress[$cnt]['imgs'] = $imgpath;
}else{
$ress[$cnt]['imgs'] = '/wp-content/uploads/2022/03/fairfax-4670d9c9.jpeg';
}
$cnt++;
}
}
echo json_encode($ress);
}
Is there a way to simply use conditions in order to put those values first in the array?
Using a function get_post_meta in an array is bad practice. I would advise first querying the database to extract data from custom fields.
However, I think there are two ways to answer your question:
Use 2 arrays and merge them together after iteration:
$myresults = $wpdb->get_results( $sqlStatement );
$ress1 = $ress2 = array();
$cnt = 0;
$imgpath = '';
if(count($myresults)>0){
foreach ($myresults as $key => $value) {
$id = $value->ID;
if(get_post_meta($id,'_awpcp_extra_field[36]',true) !='' && get_post_meta($id,'_awpcp_extra_field[37]',true) != ''){
$is_featured = get_post_meta($id,'_awpcp_is_featured',true);
$imgpath = get_the_post_thumbnail_url($id,'dailymag-featured');
$array_name = !empty($is_featured) ? 'ress1' : 'ress2';
$$array_name[$cnt]['featured'] = $is_featured;
if($imgpath){
$$array_name[$cnt]['imgs'] = $imgpath;
}else{
$$array_name[$cnt]['imgs'] = '/wp-content/uploads/2022/03/fairfax-4670d9c9.jpeg';
}
$cnt++;
}
}
$ress = array_merge($ress1, $ress2);
echo json_encode($ress);
}
Use 2 counters:
$myresults = $wpdb->get_results( $sqlStatement );
$ress = array();
$cnt1 = 0;
$cnt2 = 1000000;
$imgpath = '';
if(count($myresults)>0){
foreach ($myresults as $key => $value) {
$id = $value->ID;
if(get_post_meta($id,'_awpcp_extra_field[36]',true) !='' && get_post_meta($id,'_awpcp_extra_field[37]',true) != ''){
$is_featured = get_post_meta($id,'_awpcp_is_featured',true);
$imgpath = get_the_post_thumbnail_url($id,'dailymag-featured');
$counter_name = !empty($is_featured) ? 'cnt1' : 'cnt2';
$ress[$$counter_name]['featured'] = get_post_meta($id,'_awpcp_is_featured',true);
$imgpath = get_the_post_thumbnail_url($id,'dailymag-featured');
if($imgpath){
$ress[$$counter_name]['imgs'] = $imgpath;
}else{
$ress[$$counter_name]['imgs'] = '/wp-content/uploads/2022/03/fairfax-4670d9c9.jpeg';
}
$$counter_name++;
}
}
$ress = array_values( $ress );
echo json_encode($ress);
}
I am unable to enter multiple data, it enter only single data. I have tried using for loop and then entering data, using 3 user and 2 task, there is an error previously offset.
public function add($postData)
{
// dd($postData);
$c = count($postData['user_name']);
$t = count($postData['task_name']);
for ($i = 0; $i < $c; $i++) {
$user_name = $postData['user_name'][$i];
$user_email = $postData['user_email'][$i];
$data['insert']['user_name'] = $user_name;
$data['insert']['user_email'] = $user_email;
}
for ($j = 0; $j < $t; $j++) {
$task_name = $postData['task_name'][$j];
$data['insert']['task_name'] = $task_name;
}
$data['insert']['name'] = $postData['name'];
$data['insert']['description'] = $postData['description'];
$data['insert']['customer_name'] = $postData['customer_name'];
$data['insert']['billing_method'] = $postData['billing_method'];
$data['insert']['dt_created'] = DT;
$data['table'] = PROJECT;
$result = $this->insertRecord($data);
if ($result == true) {
$response['status'] = 'success';
$response['message'] = 'Project created';
} else {
$response['status'] = 'danger';
$response['message'] = DEFAULT_MESSAGE;
}
return $response;
}
As Per lack of question details attached, I am supposing that you want to insert multiple task entry with project name, description etc.
Here is updated code:
<?php
// dd($postData);
$username = $postData['username'];
$user_email = $postData['user_email'];
$task_name = $postData['task_name'];
foreach ($username as $key => $value) {
$data['insert']['name'] = $postData['name'];
$data['insert']['description'] = $postData['description'];
$data['insert']['customer_name'] = $postData['customer_name'];
$data['insert']['billing_method'] = $postData['billing_method'];
$data['insert']['username'] = $value;
$data['insert']['user_email'] = $user_email[$key];
$data['insert']['task_name'] = $task_name[$key];
$data['insert']['dt_created'] = DT;
$data['table'] = PROJECT;
$result = $this->insertRecord($data);
}
The data does not want to loop. When it is stored that is stored only the topmost data only. I want to change the model in codeigniter not allowed to use the code.
public function saveTrans1(){
$product = $this->input->post('product');
$product_id = $this->input->post('product_id');
$salutation = $this->input->post('salutation');
$fullname = $this->input->post('fullname');
$email = $this->input->post('email');
$company = $this->input->post('company');
$jobtitle = $this->input->post('jobtitle');
$address = $this->input->post('address');
$phonenumber = $this->input->post('phonenumber');
$personal = $this->input->post('personal');
$industry = $this->input->post('industry');
$y = count($salutation);
$nom=0;
$nom++;
for ($i = 0; $i < $y; $i++) {
$postData['salutation'] = $salutation[$i];
$postData['fullname'] = $fullname[$i];
$postData['email'] = $email[$i];
$postData['company'] = $company[$i];
$postData['jobtitle'] = $jobtitle[$i];
$postData['address'] = $address[$i];
$postData['phonenumber'] = $phonenumber[$i];
$postData['personal'] = $personal[$i];
$postData['industry'] = $industry[$i];
$postData['product_name']=$product;
$postData['product_id']=$product_id;
$postData['password']=$this->randomKey(6);
//print ($i);
$this->v2->inject_transaction_member($postData);
}
}
I am currently working on a search function for my site and I returning the results in JSON. However, some values are returning after returning the first results like the following:
{"fullname":"test name","occupation":"test","industry":"testing","bio":"i am testing stuff.","gender":"f","website":"http:\/\/yhisisasite.com","skills":["writing","reading","math","coding","baseball"],"interests":["coding","sampling","googling","typing","playing"]},{"fullname":null,"occupation":null,"industry":null,"bio":null,"gender":null,"website":null,"skills":["coding","docotrs","soeku","spelling"],"interests":["testing","wintro","skating","hockey","code"]}
I currently have a class to work as a template for the results which looks like this:
class SearchResultUserProfile {
public $fullname = "";
public $occupation = "";
public $industry = "";
public $bio = "";
public $gender = "";
public $website = "";
public $skills = array();
public $interests = array();
}
Then to populate those fields I have a few loops during the mysqli fetch:
while ($row = mysqli_fetch_array($result))
{
$max = sizeof($user_id_array);
for($i = 0; $i < $max; $i++)
{
//create a new instance or object
$searchResultUserProfile = new SearchResultUserProfile();
$searchResultUserProfile->fullname = $row['fullname'];
$searchResultUserProfile->occupation = $row['occupation'];
$searchResultUserProfile->industry = $row['industry'];
$searchResultUserProfile->bio = $row['bio'];
$searchResultUserProfile->gender = $row['gender'];
$searchResultUserProfile->website = $row['website'];
//grab the interests and skills
$skillDetails = fetchAllUserSkills($user_id_array[$i]);
foreach($skillDetails as $row) {
$thistest = $row['skills'];
array_push($searchResultUserProfile->skills, $thistest);
}
$interestDetails = fetchAllUserInterests($user_id_array[$i]);
foreach($interestDetails as $row) {
$thistests = $row['interests'];
array_push($searchResultUserProfile->interests, $thistests);
}
array_push($results, $searchResultUserProfile);
}
echo json_encode($results);
}
Any idea why this is happening? Is it how I am iterating through the loop or the set up? I am sure I am overlooking something simple but I cannot figure out what it is.
The problem is that you are overwriting your $row variable in the inner loops:
while ($row = mysqli_fetch_array($result))
^^^^ this is a result row from your query
{
$max = sizeof($user_id_array);
for($i = 0; $i < $max; $i++)
{
$searchResultUserProfile = new SearchResultUserProfile();
$searchResultUserProfile->fullname = $row['fullname'];
...
foreach($skillDetails as $row) {
^^^^ here you are overwriting your query result
...
}
...
}
echo json_encode($results);
}
So if $max is more than 1, from the second iteration on you will be using the last result of your last inner loop. And that will not be the result from the query that you expect it to be.
I am trying to save an object with a variable amount of "cols". The number of cols is equal to the number of headers. This is how the code looked before:
if(isset($_POST['submit'])){
$sub = new Sub();
$sub->product_id = $_POST['product_id'];
$sub->col1 = $_POST['col1'];
$sub->col2 = $_POST['col2'];
$sub->col3 = $_POST['col3'];
$sub->col4 = $_POST['col4'];
$sub->col5 = $_POST['col5'];
$sub->col6 = $_POST['col6'];
$sub->col7 = $_POST['col7'];
$sub->col8 = $_POST['col8'];
$sub->col9 = $_POST['col9'];
$sub->col10 = $_POST['col10'];
$sub->col11 = $_POST['col11'];
$sub->col12 = $_POST['col12'];
$sub->col13 = $_POST['col13'];
$sub->col14 = $_POST['col14'];
$sub->col15 = $_POST['col15'];
This is how I want it to look:
if(isset($_POST['submit'])){
$sub = new Sub();
$sub->product_id = $_POST['product_id'];
$i = 0;
foreach($headers as $header){
$i++ ;
$sub->col.$i = $_POST['col'.$i];
}
How do I pass the variable $i into the object's attributes? $sub->(col.$i) ? $sub->(col{$i}) ? Please help me figure this out =) Thank you
Try this:
$sub = new Sub();
$sub->product_id = $_POST['product_id'];
for($i = 1; $i <= count($headers); ++$i)
$sub->{'col' . $i} = $_POST['col' . $i];
But, this is really not the way that the columns should be stored in the Sub object, you should use an array:
$sub->columns = array();
for($i = 1; $i <= count($headers); ++$i) {
$sub->columns[] = $_POST['col' . $i];
}
You have to use {} :
$sub->{'col' . $i} = ...
$field = "col$i";
$sub->$field = "whatver"
I'd prefer a setter method.
class Sub {
public function set($attribute, $value) {
$this->$attribute = $value;
}
}
Now you can do:
foreach($_POST as $key => $value) {
$sub->set($key, $value)
}
Or without the loose coupling:
$i = 1;
while($value = $_POST['col' . $i]) {
$sub->set('col' . $i, $value);
$i++;
}