PHP foreach loop JSON - php

I know there are like hundreds similar questions on this site, but I just can't get my code working...
I have this JSON
{
"version":"1.0.0",
"buildDate":20131029,
"buildTime":165127,
"lockPath":"..\\var\\lock",
"scriptPath":"..\\var\\lock",
"connections":
[
{
"name":"o016561",
"bez":"GEW-NRW",
"type":"OVPN"
},
{
"name":"o016482",
"bez":"GEW-BW",
"type":"OVPN"
},
{
"name":"o019998",
"bez":"GEW-SH",
"type":"OVPN"
}
]}
how can I access the "name" values to check if there's an existing file with an equal name?
I tried
$json_config_data = json_decode(file_get_contents($json_path,true));
foreach($json_config_data->connections as $connectionName)
{
if($connectionName->name == $fileName)
{
$status = 1;
}
else
{
$status = 0;
}
}
but I always get $status = 0...
I think there's an easy solution for this, but I'm pretty new to PHP so I'd be glad for any kind of help.
Thanks in advice

You're resetting the value of $status for every iteration which means that the last connection HAS to be the correct one. You're probably looking for a break statement.
$json_config_data = json_decode(file_get_contents($json_path,true));
$status = 0; //Default to 0
foreach($json_config_data->connections as $connectionName)
{
if($connectionName->name == $fileName)
{
$status = 1;
break; //End the loop
}
}

This would only result in $status == 1 if the final name matched your requirements; otherwise you're setting $status back to 0. You should break out of the loop when you find a match:
$status = 0;
foreach ($json_config_data->connections as $connectionName) {
if ($connectionName->name == $fileName) {
$status = 1;
break; // this breaks out of the foreach loop
}
}

Related

assign variable if condition match in for loop

Suppose I have an array with ie. $user_all_activity in code, i must check 5 activity in 10 minute(which is done by getDifference(),which return true is condition matches).If condition matched the condition,now i must check 5 activity in 10 minute after the condition matched.And this will be repeated several times.I put some late night programming here.
//$$user_all_activity take all activity of user A
if(!$user_all_activity == NULL)
{
$size = sizeof($user_all_activity);
//$prev_array = array();
for( $i=0; $i<$size-1;$i++)
{
if($i>3)
{
$prev_array = $user_all_activity[$i-4];
$current_array = $user_all_activity[$i];
//get difference check for difference 10
if($this->getDifference($current_array,$prev_array))
{
echo "Table update at id ".$current_array['id']." </br>";
}
}
}
}
The problem for me when condition matched.I must check again the same thing.May be good to use recursive.Sorry for not explaining the problem before.Hope you get the question.Thanks
Set a variable, and then check it later.
if($user_all_activity != NULL)
{
$size = sizeof($user_all_activity);
$difference_found = false;
for( $i=0; $i<$size-1;$i++)
{
if($i>3)
{
$prev_array = $user_all_activity[$i-4];
$current_array = $user_all_activity[$i];
//get difference check for difference 10
if($this->getDifference($current_array,$prev_array))
{
echo "Table update at id ".$current_array['id']." </br>";
$difference_found = true;
}
if ($difference_found) {
// do something
}
}
}
}

Is it possible to create a for loop inside an if condition?

I need to check if some text areas are set, but there might be a lot of them. I want to check if every single one of them is set inside an if statement with a for loop.
if(//for loop here checking isset($_POST['item'.$i]) )
You could do this:
// Assume all set
$allSet = true;
// Check however many you need
for($i=0;$i<10;$i++) {
if (!isset($_POST['item'.$i])) {
$allSet=false; // If anything is not set, flag it and bail out.
break;
}
}
if ($allSet) {
//do stuff
} else {
// do other stuff
}
If you've only a few, or they're not sequential there's no need for a loop. You can just do:
if (isset($_POST['a'], $_POST['d'], $_POST['k']....)) {
// do stuff if everything is set
} else {
// do stuff if anything is not set
}
try using this:
$post=$_POST;
foreach($post as $key=>$value){
if (isset($value) && $value !="") {
// do stuff if everything is set
} else {
// do stuff if anything is not set
}
You can try:
<?php
$isset = true;
$itemCount = 10;
for($i = 0; $i < $itemCount && $isset; $i++){
$isset = isset($_POST['item'.$i]);
}
if ($isset){
//All the items are set
} else {
//Some items are not set
}
I'm surprised that after three answers, there isn't a correct one. It should be:
$success = true;
for($i = 0; $i < 10; $i++)
{
if (!isset($_POST['item'.$i]))
{
$success = false;
break;
}
}
if ($success)
{
... do something ...
}
Many variation are possible, but you can really break after one positive.
Yes, one may have a loop within an if-condtional. You may use a for-loop or you may find it more convenient to use a foreach-loop, as follows:
<?php
if (isset($_POST) && $_POST != NULL ){
foreach ($_POST as $key => $value) {
// perform validation of each item
}
}
?>
The if conditional basically tests that a form was submitted. It does not prevent an empty form from being submitted, which means that any required data must be checked to verify that the user provided the information. Note that $key bears the name of each field as the loop iterates.

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

GET Multiple MySQL Rows, Form PHP Variables, and Put Into Json Encoded Array

I am trying to GET different rows from different columns in php/mysql, and pack them into an array. I am able to successfully GET a jason encoded array back IF all values in the GET string match. However, if there is no match, the code echos 'no match', and without the array. I know this is because of the way my code is formatted. What I would like help figuring out, is how to format my code so that it just displays "null" in the array for the match it couldn't find.
Here is my code:
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode($fbaddra);
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['addr'];
} else {
$fbaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['addr'];
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
UPDATE: The GET Request
I would like the GET request below to return the full array, with whatever value that didn't match as 'null' inside the array.
domain.com/api/core/engine.php?a=fbaddra&facebook=username&facebookp=pagename
The GET above currently returns null.
Requests that work:
domain.com/api/core/engine.php?a=fbaddra&facebook=username or domain.com/api/core/engine.php?a=fbaddra&facebookp=pagename
These requests return the full array with the values that match, or null for the values that don't.
TL;DR
I need assistance figuring out how to format code to give back the full array with a value of 'null' for no match found in a row.
rather than assigning as 'null' assign null. Your full code as follows :
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode('no match');
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
You can even leave else part altogether.
Check your code in this fragment you not use same names for variables:
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = 'null';
}
$fbaddr not is same as $fpaddr, this assign wrong result to if statement.
It was the mysql query that was the problem.
For those who come across this, and need something similar, you'll need to format your query like this:
** MYSQL QUERY **
if ($_GET['PUTVALUEHERE']) {
$g = $_GET['PUTVALUEHERE'];
$gq = $mysqli->real_escape_string($g);
$q1 = "SELECT * FROM `addrbook` WHERE `facebookp` = '".$gq."' OR `facebook` = '".$gq."'";
}
** PHP CODE **
if($_GET['PUTVALUEHERE']{
echo json_encode($row['addr']);
}

PHP recently viewed script to session array

I've been given this bit of code:
if(isset($_GET['viewevent'])) {
if(count($_SESSION['e_lastviewed']) == 0) {
$_SESSION['e_lastviewed'][0] = $_GET['viewevent'];
} else if(!in_array($_GET['viewevent'], $_SESSION['e_lastviewed'])) {
$_SESSION['e_lastviewed'][2] = $_SESSION['e_lastviewed'][1];
$_SESSION['e_lastviewed'][1] = $_SESSION['e_lastviewed'][0];
$_SESSION['e_lastviewed'][0] = $_GET['viewevent'];
}
}
if($_GET['show']) {
$_SESSION['show'] = $_GET['show'];
} else if($_SESSION['show']=='') {
$_SESSION['show'] = "all";
}
It apparently saves ID's of recently viewed items, so i need to put these id's into an array.
Would this work?
$my_array = array($_SESSION['e_lastviewed'][2],$_SESSION['e_lastviewed'][1],$_SESSION['e_lastviewed'][0]);
I've ran it but it displays blank results (not sure if thats due to me not doing it right or incomplete code...Have i missed something? I'm not sure if i completley understand the script i was given...
try this:
if ( !isset($_SESSION['e_lastviewed']) )
$_SESSION['e_lastviewed'] = array();
// alt: while(count($_SESSION['e_lastviewed']) > 2 ) {
if(count($_SESSION['e_lastviewed']) > 2 ) {
array_shift($_SESSION['e_lastviewed']); // drop off from 3
array_unshift($_SESSION['e_lastviewed'],$_GET['viewevent']); // insert in the beginning
if($_GET['show']) {
$_SESSION['show'] = $_GET['show'];
} else if($_SESSION['show']=='') {
$_SESSION['show'] = "all";
}

Categories