I am saving data in JSON file for retrieving after redirect. If I check if the value matches in the json array, I always get false and something must be wrong, but I cannot figure it out. How can I the object with the specific SSL_SESSION_ID
Here's my json
[
{
"SSL_CLIENT_S_DN_CN": "John,Doe,12345678912",
"SSL_CLIENT_S_DN_G": "JOHN",
"SSL_CLIENT_S_DN_S": "DOE",
"SSL_CLIENT_VERIFY": "SUCCESS",
"SSL_SESSION_ID": "365cb4834f9d7b3d53a3c8b2eba55a49d5cac0112994fff95c690b9079d810af"
},
{
"SSL_CLIENT_S_DN_CN": "John,Doe,12345678912",
"SSL_CLIENT_S_DN_G": "JOHN",
"SSL_CLIENT_S_DN_S": "DOE",
"SSL_CLIENT_VERIFY": "SUCCESS",
"SSL_SESSION_ID": "e7bd2b6cd3db89e2d6fad5e810652f2ae087965e64b565ec8933b1a67120b0ac"
}
]
Here's my PHP script, which always returns It doesn't match
$sslData = Storage::disk('private')->get('ssl_login.json');
$decodedData = json_decode($sslData, true);
foreach ($decodedData as $key => $items) {
if ($items['SSL_SESSION_ID'] === $SSL_SESSION_ID) {
dd("It matches");
} else {
dd("It doesn't match");
}
}
Your script will always end after the first iteration, since you're using dd() regardless if it was a match or not and you will always get the "no-match"-message if the first iteration isn't a match.
You should iterate through all the items and then see if there was a match or not:
$match = null;
foreach ($decodedData as $key => $items) {
if ($items['SSL_SESSION_ID'] === $SSL_SESSION_ID) {
$match = $items;
// We found a match so let's break the loop
break;
}
}
if (!$match) {
dd('No match found');
}
dd('Match found');
That will also save the matching item in the $match variable if you need to use the data somehow.
Related
I'm trying to set up a test question that will find certain words in a short answer. The words, which will mark the answer as correct, will be stored as values in an object. I was trying to figure out how to do it with strpos(), but every alternative that I come up with gives me a blank screen.
PHP:
$myJSON = file_get_contents('quiz.json');
$json = json_decode($myJSON);
foreach($json as $value) {
foreach($value->answer as $index => $options) {
$findme = "application";
$pos = strpos($options, $findme);
if ($pos === true) {
echo $options;
//echo $value->text->type->answer;
//echo ($index. ' '. $options . '<br>');
//echo current($value);
}
}
}
JSON:
{
"question1": {
"text": "What are the two types of permission lists that DSA concentrates on?",
"type": "short_answer",
"answer": {
"1": "application",
"2": "row-level"
}
},
"question2": {
"text": "What are the building blocks for EmpowHR Security?",
"type": "short_answer",
"answer": {
"1": "permission lists"
}
},
"question3": {
"text": "Who is the bomb?",
"type": "short_answer",
"answer": {
"1": "permission"
}
}
}
Tested the following using your given JSON file.
Important: First I added the , true to $json = json_decode($myJSON); --> $json = json_decode($myJSON, true); This turns the obj into an array
After var_dumping the json encoded I noticed you had mixed string and array types in the level you were trying to parse, so used in_array() to filter out the strings and only iterate through the arrays and was able to locate all instances of the "answers" section in its current build within that obj.
$stmt = NULL;
$find = "application";
$myJSON = file_get_contents('quiz.json');
$json = json_decode($myJSON, true);
foreach( $json as $content ){
foreach( $content as $target){
if(is_array($target)){
// we must find the key of the value within the next level of the array
// and use it as index for the value $target to use in strpos() --> $target[$index]
foreach($target as $index => $value){
if(strpos($target[$index], $find) !== false){
$stmt = '<span>'.$target[$index].': CORRECT</span>';
}
}
}
}
}
echo $stmt;
foreach( $json as $question=>$content ){
foreach( $content as $key=>$value ){
if( strpos( $value, 'applikation' ) !== false
echo $value;
}
}
}
strpos returns the found position and false if not found.
returnvalue === true: allways false
returnvalue == true: false if not found or found on first position (0), true if found after first position (all numbers != 0 are true)
returnvalue !== false: correct result
I have a json file.
{
"whitepapers": {
"1": {
"name": "The Title of the Doc",
"file": "the-title-of-the-doc",
"asset_description": "blah blah",
"image": "/img.png",
"formId": "xxx",
"confirmation": true
},
"0": {
"name": "The Title of the Doc 2",
"file": "the-title-of-the-doc-2",
"asset_description": "blah blah",
"image": "/img.png",
"formId": "xxx",
"confirmation": true
}
},
there is a page-handler.php that already takes information from this json file and creates pages from them:
if (strpos($shortPage, 'whitepapers') !== false) { // test for Whitepapers overview page
require $contentPath . 'resources_whitepapers.php';
} else if (($aPosition=strpos($shortPage, 'whitepaper')) !== false) { // test for whitepaper asset page & grab where in string if positive
$aString = mb_substr($shortPage, ($aPosition + 10)); // strip everything from the string up to the end of the found string
$aString = ltrim($aString, '/'); // remove the preceding "/" if it exists
$json_string = $contentPath . 'asset-manifest.json'; // point to the asset manifest list [in json format] TODO: error handling here
$jsondata = file_get_contents($json_string); // load it into memory
$obj = json_decode($jsondata,true); // decode it into an array
foreach ($obj['whitepapers'] as $key => $value) { // Find the parent of our string's key/value pair in the multidimensional json array
foreach ($value as $_key => $_value) {
if ($_key === 'file' && $_value === $aString) { // look for the asset string value in the 'file' key
$match = $key; // found a match, grab the pair's parent array
}}}
if ($match >= 0) { // found a match in the manifest, render the page
require $contentPath . 'whitepaper-template.php';
} else { // can't find a match in the manifest
include $errorPagePath; // return a 404 page and handle the error
}
} else if....
The dev who made this originally is no longer here so I can't ask him to walk me through it.
I want to be able to check if "confirmation": true and then funnel into a confirmation-temaplte.php like how the above funnels into a whitepaper-template.php and then else "confirmation": false it doesn't do anything
I've tried copying the code over from page-handler.php into a else if ("confirmation":true){blah} and making a confirmation-template.php but I wasn't sure if I was targeting "confirmation" correctly.
Then I noticed it started messing up the other pages that are dependent on the json file. It seems when I make a confirmation-template.php page it messes up the other pages using a xxx-template.php file and I'm unsure why.
As you see, I'm a bit new at PHP Templating and JSON information access. Thanks for the help
foreach ($obj['whitepapers'] as $key => $value) { // Find the parent of our string's key/value pair in the multidimensional json array
if ($value['confirmation'] ?? false) {
// here Is your confirmation === true
}
foreach ($value as $_key => $_value) {
if ($_key === 'file' && $_value === $aString) { // look for the asset string value in the 'file' key
$match = $key; // found a match, grab the pair's parent array
}}}
I've written the following block of code to find if a word exists in a grid of nodes.
function findWord() {
$notInLoc = [];
if ($list = $this->findAll("a")) {
foreach($list as $node) {
$notInLoc[] = $node->loc;
if ($list2 = $this->findAllConnectedTo($node, "r", $notInLoc)) {
foreach($list2 as $node2) {
$notInLoc[] = $node2->loc;
if ($list3 = $this->findAllConnectedTo($node2, "t", $notInLoc)) {
foreach($list3 as $node3) {
return true;
}
}
}
}
}
}
return false;
}
This "works" and passes all my 3-letter word test cases because I've hard-coded the characters I'm looking for and I know how long the word is. But what I need to do is pass in any word, regardless of length and letters, and return true if I found the word against all these restrictions.
To summarize the algorithm here:
1) I find all the nodes that contain the first character "a" and get a list of those nodes. That's my starting point.
2) For each "a" I'm looking for all the "r"s that are connected to it but not in a location I'm already using. (Each node has a location key, and that key is stored in the notInLoc array while looking through it. I realize that this may break though because notInLoc is only being reset the first time I enter the function so every time I go through the foreach it keeps pushing the same location in.
3) Once I've found all the "r"s connected to the "a" I'm currently on, I check to see if there are any "t"s connected to the "r"s. If there is at least 1 "t" connected, then I know the word has been found.
I'm having trouble refactoring this to make it dynamic. I'll give you the idea I was working with, but it is broken.
function inner($word, $list, $i = 0, $notInLoc = []) {
$i++;
foreach($list as $node) {
$notInLoc[] = $node->loc;
if ($list2 = $this->findAllConnectedTo($node, $word[$i], $notInLoc)) {
if ($i == (strlen($word) - 1)) {
return true;
} else {
$this->inner($word, $list2, $i, $notInLoc);
}
}
}
return false;
}
function findWord2($word) {
if ($list = $this->findAll($word[0])) {
return $this->inner($word, $list);
}
return false;
}
I understand that there are other ways to solve problems like this, but I need it to work using only the functions findAll which returns all nodes with a specific value, or false and findAllConnectedTo which returns all nodes with a specific value connected to a node that are not contained on the "Do Not Use" notInLoc list.
You need to pass result through all nested contexts to the top, because found word will eventually return true, but it will vanish in upper level (continue loop and return false). Try this:
if ($list2 = $this->findAllConnectedTo($node, $word[$i], $notInLoc)) {
if ($i == strlen($word) - 1 || $this->inner($word, $list2, $i, $notInLoc)) {
return true;
}
}
Next I'd take care of $word needlesly passed around. It stays the same for all contexts - only pointer changes.
I want to search string in json and remove it, but my code doesn't work,
this example of json :
{
d: {
results: [
{
name: "first",
Url: "http://example.com/tes.pdf"
},
{
name: "second",
Url: "http://example.com/download/qwdahfvajvlaksjkjdfaklfaf"
}
]
}
}
and this my php code :
$result = file_get_contents("cache.json");
$jsonObj = json_decode($result);
foreach($jsonObj->d->results as $key => $value) {
if(strpos($value->Url, '.pdf') !== true) {
unset($key->$value);
}
}
echo json_encode($jsonObj);
in this case, i want to remove element second is not contain url ".pdf",
anyone can help me?
try this:
$result = '{"d":{"results":[{"name": "first","Url": "http://example.com/tes.pdf"},{"name": "second","Url": "http://example.com/download/qwdahfvajvlaksjkjdfaklfaf"}]}}';
$jsonArr= json_decode($result, true); //this is an array
foreach($jsonArr['d']['results'] as $key => $value) {
if(strpos($value['Url'], '.pdf') !== false) {
continue; //found so not interested in it
} else {
unset($jsonArr['d']['results'][$key]);
}
}
echo json_encode($jsonArr);
When I work with keys and values, I like to convert (if needed) it to an array. It's easier to understand and manipulate.
Hope this helps! :D
Your best bet would be converting it to an array, using json_decode(); from there, you can iterate through your array. If it stays in the same structure, then something like the following should work:
<?php
$a = $array['d']['results'];
foreach($a as $b => $c) {
if(strpos($c['Url'], '.pdf') !== FALSE) {
// Found
} else {
unset($a[$b]); // Unset in original array.
}
}
I know this question has been asked before but I haven't been able to get the provided solutions to work.
I'm trying to check if the words in an array match any of the words (or part of the words) in a provided string.
I currently have the following code, but it only works for the very first word in the array. The rest of them always return false.
"input" would be the "haystack" and "value" would be the "needle"
function check($array) {
global $input;
foreach ($array as $value) {
if (strpos($input, $value) !== false) {
// value is found
return true;
} else {
return false;
}
}
}
Example:
$input = "There are three";
if (check(array("one","two","three")) !== false) {
echo 'This is true!';
}
In the above, a string of "There is one" returns as true, but strings of "There are two" or "There are three" both return false.
If a solution that doesn't involve having to use regular expressions could be used, that would be great. Thanks!
The problem here is that check always returns after the first item in $array. If a match is found, it returns false, if not, it returns true. After that return statement, the function is done with and the rest of the items will not be checked.
function check($array) {
global $input;
foreach($array as $value) {
if(strpos($input, $value) !== false) {
return true;
}
}
return false;
}
The function above only returns true when a match is found, or false when it has gone through all the values in $array.
strpos(); is totally wrong here, you should simply try
if ($input == $value) {
// ...
}
and via
if ($input === $value) { // there are THREE of them: =
// ...
}
you can even check if the TYPE of the variable is the same (string, integer, ...)
a more professional solution would be
in_array();
which checks for the existance of the key or the value.
The problem here is that you're breaking out of the function w the return statement..so u always cut out after the first comparison.
you should use in_array() to compare the array values.
function check($array) {
global $input;
foreach ($array as $value) {
if (in_array($value,$input))
{
echo "Match found";
return true;
}
else
{
echo "Match not found";
return false;
}
}
}
You're returning on each iteration of $array, so it will only run once. You could use stristr or strstr to check if $value exists in $input.
Something like this:
function check($array) {
global $input;
foreach ($array as $value) {
if (stristr($input, $value)) {
return true;
}
}
return false;
}
This will then loop through each element of the array and return true if a match is found, if not, after finishing looping it will return false.
If you need to check if each individual item exists in $input you'd have to do something a little bit different, something like:
function check($array) {
global $input;
$returnArr = array();
foreach ($array as $value) {
$returnArr[$value] = (stristr($input, $value)) ? true : false;
}
return $returnArr;
}
echo '<pre>'; var_dump(check($array, $input)); echo '</pre>';
// outputs
array(3) {
["one"]=>
bool(false)
["two"]=>
bool(false)
["three"]=>
bool(true)
}
The reason your code doesnt work, is because you are looping through the array, but you are not saving the results you are getting, so only the last result "counts".
In the following code I passed the results to a variable called $output:
function check($array) {
global $input;
$output = false;
foreach ($array as $value) {
if (strpos($input, $value) != false) {
// value is found
$output = true;
}
}
return $output;
}
and you can use it like so:
$input = "There are two";
$arr = array("one","two","three");
if(check($arr)) echo 'this is true!';