If Else Echo JSON array check - php

I have a JSON array that I am pulling values from per $vars. Within the JSON data are going to be some key words that I am looking for. I have a single if else that looks like:
(demonstration purposes)
if( $FullName == $Data[$c]['manager'] $FullName == $Data[$c]['leader'] || $FullName == $Data[$c]['helper']) {
$cheapLabor = 'NO';
} else {
$cheapLabor = 'YES';
}
That works great however, now I want to define more specifically some if else points on status points which would represent their employement status. Each Emp Status is based on a group.
I would need it to check from the top of the food chain, then go downward to check if status = x. If it does then $cheapLabor = 'y'; else $cheapLabor = 'z';
I tried doing it, but I can't seem to get it to work. Here is what I am working with:
$repData = json_decode($json, TRUE);
$c = 0;
$var = $repData[$c]['column'];
if($FullName == $repData[$c]['ceo']) {
$groups = '[13]';
} else {
$groups = '[5]';
}
if($FullName == $repData[$c]['director']) {
$groups = '[10]';
} else {
$groups = '[5]';
}
if($FullName == $repData[$c]['regional']) {
$groups = '[9]';
} else {
$groups = '[5]';
}
if($FullName == $repData[$c]['project_manager']) {
$groups = '[8]';
} else {
$groups = '[]';
}
if($FullName == $repData[$c]['team_leader']) {
$groups = '[6]';
} else {
$groups = '[5]';
}
if($FullName == $repData[$c]['rae']) {
$groups = '[5]';
} else {
$staus = '[5]';
}
Shomz Answer partial working...
$groups = '[4]'; // new hire group default, to be overwritten if a user has the correct title within Table.
$roleGroups = array(
'regional' => '[7]',
'team_leader' => '[6]',
'RAE' => '[5]'
);
foreach ($roleGroups as $role => $groups) { // go through all the Position Titles
if ($FullName == $repData[$c][$role]) { // see if there's a match
$repGroup = $groups; // if so, assign the group
}
}
It sets team_leader and regional correctly but anything else just sets it as regional group.
Just realized that its actually rewriting the value.

Your code is overwriting $groups in every if-statement. You probably want to rewrite that in a switch/case statement with a default value being [5].
Let's say the first if is true, so $FullName == $repData[$c]['ceo'] is true and $groups becomes [13]. In the next line, there are two choices:
either a person is a director (AND a CEO, but it doesn't matter, see why below)
or a person is not a director (could be a CEO)
In both cases, $groups will either get a value of [10] or [5], meaning that no matter what happened inside the statement above, this statement will overwrite it. Thus, only your last if statement is able to produce results you might expect.
"Only one group per role"
In that case a simple switch/case statement will work:
switch($FullName){
case ($repData[$c]['ceo']):
$groups = '[13]';
break;
case ($repData[$c]['director']):
$groups = '[10]';
break;
// etc... for other roles
default:
$groups = '[5]';
break;
}
Or you can go even simpler and use an associative array to combine roles with group numbers. For example:
$roleGroups = array('ceo' => '[13]', 'director' => '[15]', etc);
Then simply see if there's a match:
$groups = '[5]'; // default, to be overwritten if a role is found below
foreach ($roleGroups as $role => $group) { // go through all the groups
if ($FullName == $repData[$c][$role]) { // see if there's a match
$groups = $group; // if so, assign the group
}
}
Hope this makes sense. Either way, $groups will have the number of the role if role is found, 5 otherwise.

Related

If statement never evaluates to true (even when it should)

I'd created an if statement "if ($user_roles == 3) " and this $user_roles has a value of "3" the condition is supposed to be true but the result is always false.
here is my code below:
public function ViewSponsorInfo($sponsor_id)
{
$id = $sponsor_id;
$user_id = User::where('id','=',$id)->get();
$user_roles = [];
foreach ($user_id as $id) {
array_push($user_roles, $id->role);
}/*
dd($user_roles);*/
if ($user_roles == 3) {
$orga = Organization::where('orga_id','=',$sponsor_id)->get();
dd($orga);
return view('pages.Ngo.View-Sponsor-Information',compact('orga'));
}else{
$indi = Individual::where('indi_id','=',$sponsor_id)->get();
dd($indi);
return view('pages.Ngo.View-Sponsor-Information',compact('indi'));
}
}
$user_rolesis not 3 and can never be. it's an array.
its contents, however, can be three.
try:
if(in_array(3, $user_roles)) { ...}
for reference: in_array
$user_roles is an array. So your if statement is always false.
I think, try this one.
foreach ($user_id as $id) {
array_push($user_roles, array('role' => $id->role));
}/*
dd($user_roles);*/
foreach ($user_roles as $user_role) {
if ($user_role['role'] == 3) {
$orga = Organization::where('orga_id','=',$sponsor_id)->get();
dd($orga);
return view('pages.Ngo.View-Sponsor-Information',compact('orga'));
}else{
$indi = Individual::where('indi_id','=',$sponsor_id)->get();
dd($indi);
return view('pages.Ngo.View-Sponsor-Information',compact('indi'));
}
}
or
foreach ($user_id as $id) {
array_push($user_roles, array('role' => $id->role));
}/*
dd($user_roles);*/
foreach ($user_roles as $user_role) {
if ($user_role->role == 3) {
$orga = Organization::where('orga_id','=',$sponsor_id)->get();
dd($orga);
return view('pages.Ngo.View-Sponsor-Information',compact('orga'));
}else{
$indi = Individual::where('indi_id','=',$sponsor_id)->get();
dd($indi);
return view('pages.Ngo.View-Sponsor-Information',compact('indi'));
}
}
Please said something upon it after tried this one.
Judging from what you show your function ViewSponsorInfo() by its very name is only interested in detecting if this user has the sole role '3' in your db.
I mean the outcome is binary isn't it? Either they are a 3 or they are not, no need to go looping thru results.
$user_id = User::where('id','=',$id)->get();
if($user_id[0] !== 3 ) { //***
doSponsorLink();
}else{
doNonSponsorLink();
}
I'm not familiar with Laravel or the db layer your are using, so maybe that is even simply if($user_id).
untested, and here I am assuming user can only have 1 single role, and we do not seem to be making allowances for the user not existing in the db.

Compare numbers through a loop to set a status accordingly

Let me change my question completely to explain myself better;
I have an order;
An order have multiple order rows. Each order row has two fields; Quantity ordered, and quantity delivered.
If all order rows' quantities delivered are the same as the quantity ordered, the entire order should get a status of '100% delivered'.
If multiple or even one order row's quantities delivered does not match the quantities ordered the entire order should get a status of 'partly delivered'.
If no order row have any deliveries (if all deliveries stands on 0) the status should be '0% delivered'.
What I have so far looks only at the last order row of the entire order because all the previous rows gets overridden by the latest check. This is my code;
public function deliveryAction(Request $request, $id) {
$em = $this->getDoctrine()->getManager();
$order = $em->getRepository('QiBssBaseBundle:PmodOrder')->find($id);
$orderRowsDelivered = $request->request->all();
$delivered = "0%";
foreach ($orderRowsDelivered['order_row_id'] as $orderRowId => $quantityDelivered) {
if($quantityDelivered != '' || $quantityDelivered != null) {
$orderRow = $em->getRepository("QiBssBaseBundle:PmodOrderRow")->find($orderRowId);
$orderDelivered = new PmodDelivery();
$orderDelivered->setOrderRow($orderRow);
$orderDelivered->setQuantity($quantityDelivered);
$orderDelivered->setTimeArrived(new \DateTime());
$em->persist($orderDelivered);
$em->flush();
if($orderRow->getQuantityDelivered() > 0 && $orderRow->getQuantityDelivered() < $orderRow->getQuantity()) {
$delivered = "partly";
} elseif ($orderRow->getQuantityDelivered() == $orderRow->getQuantity()) {
$delivered = "100%";
}
}
}
var_dump($delivered);exit;
return new RedirectResponse ... ;
}
Because as of this moment he looks at the last one with 10 and 8 in the example image, and give a status of 'partly', as soon as the 'quantity delivered' amounts is entered. But he should take all rows together.
I hope this makes more sense.
Based on what Cerad in the comments of his own answer said, this is my answer; (I'll make use of OP's scenario where he uses order rows per order.)
I've added an extra property to my OrderRow entity called $rowStatus.
After that I created a getter function for the $rowStatus called getRowStatus() that gives each row a status individually;
public function getRowStatus()
{
if ($this->getQuantityDelivered() == $this->getQuantity()) {
return $this->rowStatus = 100;
} elseif ($this->getQuantityDelivered() == 0) {
return $this->rowStatus = 0;
} else {
return $this->rowStatus = 50;
}
}
After that in my Order entity I've added a $deliveryStatus property, with a corresponding getter function called getDeliveryStatus() that looks like this;
public function getDeliveryStatus()
{
if (count($this->getOrderRows()) > 0) { //this check is to make sure there are orderRows, because you can't devide by zero if it might happen that there are no order rows. If not the delivery status will just be set on 0.
$sum = 0;
foreach ($this->getOrderRows() as $row) {
$sum += $row->getRowStatus();
}
$average = $sum / count($this->getOrderRows());
if ($average == 100) {
return $this->deliveryStatus = 100;
} elseif ($average == 0) {
return $this->deliveryStatus = 0;
} else {
return $this->deliveryStatus = 50;
}
} else {
return $this->deliveryStatus = 0;
}
}
That's it! After this I just use an enum function to display the 100 as "100% delivered", the 50 as "partly delivered", and the 0 as "0% delivered". I know this isn't really necessary, and you can instead change the status number directly to a string or whatever you want to display.
Just off the top of my head I might do:
$deliveredNone = true;
$deliveredAll = true;
$deliveredSome = false;
foreach ($orderRowsDelivered['order_row_id'] as $orderRowId => $quantityDelivered) {
if ($quantityDelivered) {
$deliveredNone = false; // Know that something has been delivered
}
...
if ($orderRow->getQuantityDelivered() != $orderRow->getQuantity()) {
$deliveredSome = true;
$deliveredAll = false;
}
}
$delivered = null;
if ($deliveredNone) $delivered = '0%';
if ($deliveredAll) $delivered = '100%';
if ($deliveredSome) $delivered = 'partly';
Though I would probably just update the order with the quantities delivered then use a different function to calculate the percentage delivered. As you can see, mixing the two processes can result in confusion.

How to set a variable value based on conditions set by other variables

So I am new to PHP, and am currently just doing a little project as practice, I've managed to get down a few lines of code without falling over... but am a bit stuck here.
Essentially, what my script currently does is check three different variables that I have set (each a true/false option) and distinguishes if there is only one true option selected (out of the 3 options, only one can be true, the other 2 must be false). If only 1 value is set to true, the rest of the code runs; if multiple values are set to true, or no values are set to true, it shows an error prompt for the user.
Once this check is done, I wanted to then set the value of $name for example, based on records linked to the relevant variable that is true... This is what I have come up with, but it doesn't seem to work...
if ($value1 == "true") {$name = $result1;}
else if ($value2 == "true") {$name = $result2;}
else if ($value3 == "true") {$name = $result3;}
else exit (0)
So i essentially want to set the $name variable by identifying which of the 3 value variables is true, and then setting $name with the relevant variable retrieved in the $result
Any help would be appreciated. And before anyone goes off on one... I know I may sound a bit mad... but we all have to start somewhere!!
Thanks
It would look much nicer with a switch:
switch(true){
case $value1:
$name = $result1;
break;
case $value2:
$name = $result2;
break;
case $value3:
$name = $result3;
break;
default:
exit();
}
In case you need to make sure only one of the statements is true, validate that prior using this:
//In case you need to make there is only a single true statement
$found = false;
for($i=1; $i<4; $i++) {
$value = "value".$i;
if($$value) {
if($found) {
exit("More than one 'true' statement");
}
$found = true;
}
}
Dracony's answer looks nice indeed, but will fail when multiple values are set to true. For more flexibility, you should consider mapping the values into arrays, and tracking the state (amount of values that are true) with a flag variable. Find a fully commented example that will satisfy all conditions below. Additionally, this code will work with arrays of any length (you can add conditions by simply putting more values in $values and $results).
// store the data in arrays for easier manipulation
$values = array($value1, $value2, $value3);
$results = array($result1, $result2, $result3);
// set a flag to check the state of the condition inside the loop
// it keeps track of the index for which the value is true
$flag = -1;
$name = NULL;
// use for and not foreach so we can easily track index
for ($i = 0; $i < count($values); $i++) {
// if no index has been found 'true' yet, assign the current result.
if ($values[$i] === true) {
if ($flag === -1) {
$flag = $i;
$name = $results[$i];
}
// if a 'true' value has been found for another index
// reset the name var & stop the loop
if ($flag > -1 && $flag !== $i) {
$name = NULL;
break;
}
}
}
if ($name) {
// run code when only 1 value is true
} else {
exit();
}

foreach function only show last value

when i wanna get all value to check with current user ip it just check last ip with current user , i don't know why before values doesnt check.
i fill IPs in a textarea like this : 176.227.213.74,176.227.213.78
elseif($maintenance_for == '2') {
$get_ips = $options['ips'];
$explode_ips = explode(',',$get_ips);
foreach ($explode_ips as $ips) {
if($ips == $_SERVER["REMOTE_ADDR"]){
$maintenance_mode = true;
}
else {
$maintenance_mode = false;
}
}
}
If you found the right value, you wan't to BREAK out of the foreach loop
$get_ips = $options['ips'];
$explode_ips = explode(',', $get_ips);
foreach($explode_ips as $ips) {
if ($ips == $_SERVER["REMOTE_ADDR"]) {
$maintenance_mode = true;
break; // If the IP is right, BREAK out of the foreach, leaving $maintenance_mode to true
} else {
$maintenance_mode = false;
}
}
yes, you will always override it. Its better to set a default and only set it once:
(Edit: added #Mathlight's answer, the break, in my solution as he suggested)
$maintenance_mode = false;
foreach ($explode_ips as $ips) {
if($ips == $_SERVER["REMOTE_ADDR"]){
$maintenance_mode = true;
break;
}
}
EDIT : another solution for the record, for the points of a oneliner
$maintenance_mode = in_array($_SERVER["REMOTE_ADDR"], $explode_ips);

PHP loops to check that a set of numbers are consecutive

I'm trying to loop through a set of records, all of which have a "number" property. I am trying to check if there are 3 consecutive records, e.g 6, 7 and 8.
I think i'm almost there with the code below, have hit the wall though at the last stage - any help would be great!
$nums = array();
while (count($nums <= 3))
{
//run through entries (already in descending order by 'number'
foreach ($entries as $e)
{
//ignore if the number is already in the array, as duplicate numbers may exist
if (in_array($e->number, $num))
continue;
else
{
//store this number in the array
$num[] = $e->number;
}
//here i need to somehow check that the numbers stored are consecutive
}
}
function isConsecutive($array) {
return ((int)max($array)-(int)min($array) == (count($array)-1));
}
You can achieve the same result without looping, too.
If they just have to be consecutive, store a $last, and check to make sure $current == $last + 1.
If you're looking for n numbers that are consecutive, use the same, except also keep a counter of how many ones fulfilled that requirement.
$arr = Array(1,2,3,4,5,6,7,343,6543,234,23432,100,101,102,103,200,201,202,203,204);
for($i=0;$i<sizeof($arr);$i++)
{
if(isset($arr[$i+1]))
if($arr[$i]+1==$arr[$i+1])
{
if(isset($arr[$i+2]))
if($arr[$i]+2==$arr[$i+2])
{
if(isset($arr[$i+3]))
if($arr[$i]+3==$arr[$i+3])
{
echo 'I found it:',$arr[$i],'|',$arr[$i+1],'|',$arr[$i+2],'|',$arr[$i+3],'<br>';
}//if3
}//if 2
}//if 1
}
I haven't investigated it thoroughly, maybe can be improved to work faster!
This will confirm if all items of an array are consecutive either up or down.
You could update to return an array of [$up, $down] or another value instead if you need direction.
function areAllConsecutive($sequence)
{
$up = true;
$down = true;
foreach($sequence as $key => $item)
{
if($key > 0){
if(($item-1) != $prev) $up = false;
if(($item+1) != $prev) $down = false;
}
$prev = $item;
}
return $up || $down;
}
// areAllConsecutive([3,4,5,6]); // true
// areAllConsecutive([3,5,6,7]); // false
// areAllConsecutive([12,11,10,9]); // true
Here's an example that can check this requirement for a list of any size:
class MockNumber
{
public $number;
public function __construct($number)
{
$this->number = $number;
}
static public function IsListConsecutive(array $list)
{
$result = true;
foreach($list as $n)
{
if (isset($n_minus_one) && $n->number !== $n_minus_one->number + 1)
{
$result = false;
break;
}
$n_minus_one = $n;
}
return $result;
}
}
$list_consecutive = array(
new MockNumber(0)
,new MockNumber(1)
,new MockNumber(2)
,new MockNumber(3)
);
$list_not_consecutive = array(
new MockNumber(5)
,new MockNumber(1)
,new MockNumber(3)
,new MockNumber(2)
);
printf("list_consecutive %s consecutive\n", MockNumber::IsListConsecutive($list_consecutive) ? 'is' : 'is not');
// output: list_consecutive is consecutive
printf("list_not_consecutive %s consecutive\n", MockNumber::IsListConsecutive($list_not_consecutive) ? 'is' : 'is not');
// output: list_not_consecutive is not consecutive
If u don't wanna mess with any sorting, picking any of three numbers that are consecutive should give you:
- it either is adjacent to both the other numbers (diff1 = 1, diff2 = -1)
- the only number that is adjacent (diff = +-1) should comply the previous statement.
Test for the first condition. If it fails, test for the second one and under success, you've got your secuence; else the set doesn't comply.
Seems right to me. Hope it helps.
I think you need something like the following function (no need of arrays to store data)
<?php
function seqOfthree($entries) {
// entries has to be sorted descending on $e->number
$sequence = 0;
$lastNumber = 0;
foreach($entries as $e) {
if ($sequence==0 or ($e->number==$lastNumber-1)) {
$sequence--;
} else {
$sequence=1;
}
$lastNumber = $e->number;
if ($sequence ==3) {
// if you need the array of sequence you can obtain it easy
// return $records = range($lastNumber,$lastNumber+2);
return true;
}
}
// there isn't a sequence
return false;
}
function isConsecutive($array, $total_consecutive = 3, $consecutive_count = 1, $offset = 0) {
// if you run out of space, e.g. not enough array values left to full fill the required # of consecutive count
if ( $offset + ($total_consecutive - $consecutive_count ) > count($array) ) {
return false;
}
if ( $array[$offset] + 1 == $array[$offset + 1]) {
$consecutive_count+=1;
if ( $consecutive_count == $total_consecutive ) {
return true;
}
return isConsecutive($array, $total_consecutive, $consecutive_count, $offset+=1 );
} else {
return isConsecutive($array, $total_consecutive, 1, $offset+=1 );
}
}
The following function will return the index of the first of the consecutive elements, and false if none exist:
function findConsecutive(array $numbers)
{
for ($i = 0, $max = count($numbers) - 2; $i < $max; ++$i)
if ($numbers[$i] == $numbers[$i + 1] - 1 && $numbers[$i] == $numbers[$i + 2] - 2)
return $i;
return false;
}
Edit: This seemed to cause some confusion. Like strpos(), this function returns the position of the elements if any such exists. The position may be 0, which can evaluate to false. If you just need to see if they exist, then you can replace return $i; with return true;. You can also easily make it return the actual elements if you need to.
Edit 2: Fixed to actually find consecutive numbers.

Categories