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
Related
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 have seen so many answers but i just can't get it to work.
I want to check if there is a (partial) value in the array.
//Get DNS records
$result = dns_get_record("php.net", DNS_ALL);
print_r($result);
//If the value php-smtp3.php.net is found, echo it
if (in_array("php-smtp3.php.net", $result )) {
echo "Found!";
}
added : json_encoded $result, from my network
[
{
"host" : "php.net" ,
"class" : "IN" ,
"ttl" : 375 ,
"type" : "A" ,
"ip" : "208.43.231.9"
} ,
{
"host" : "php.net" ,
"class" : "IN" ,
"ttl" : 375 ,
"type" : "NS" ,
"target" : "dns2.easydns.net"
}
]
Thank you all so much, i think i am almost there and sorry if i dont understand fully. This is what i have now:
$result = dns_get_record("php.net", DNS_ALL);
print_r($result);
$result = json_decode($result, true);
$result = array_filter($result, function($x) {
return in_array("smtp", $x, true);
//If in the array, no matter where, is "smtp" then echo "found" is what i am trying to achieve
echo "<h1>FOUND</h1>";
});
Update:
$result = dns_get_record("php.net", DNS_ALL);
$result = json_decode($data, true);
function process($data) {
foreach ($data as $key => $value) {
if (is_array($value)) {
return process($value);
}
if (is_string($value) && strpos($value,'smtp') !== false) {
echo "FOUND";
return true;
}
}
return false;
}
$result = array_filter($result, 'process');
I am trying both ways... so sorry you guys, i am stuck trying to get a response from the DNS entry for a simple string. The actual idea behind this is:
1) Check a DNS record for a domain
2) Check if there is a SPF record ANYWHERE
3) If so, just say "found SPF record"
$values = array_reduce(
dns_get_record("php.net", DNS_ALL),
function ($out, $item) {
return array_merge($out, array_values($item));
},
[]
);
var_dump(in_array("dns2.easydns.net", $values));
//Result is bool(true)
After using json_decode, your data returns a multi dimensional array where some arrays also contain an array.
What you might do if you want to check for a partial value so if the string contains a substring is to use strpos but you have to loop throug all the strings, also in the sub arrays.
Therefore you might use array_filter in combination with a recursive approach.
So for example if you want to look for the substring smtp3 you could use:
function process($data) {
foreach ($data as $key => $value) {
if (is_array($value)) {
return process($value);
}
if (is_string($value) && strpos($value,'smtp3') !== false) {
return true;
}
}
return false;
}
$result = array_filter($result, 'process');
print_r($result);
See the php demo
All you need to do is to flatten the result and search for a value, like this:
<?php
$values = array_reduce(
dns_get_record("php.net", DNS_ALL),
function ($out, $item) {
return array_merge($out, array_values($item));
},
[]
);
var_dump(in_array("dns2.easydns.net", $values));
I am getting a list of schools for each athlete. If an athlete has a status of committed: true in the object, I only want to show that school. Otherwise, I want to return all properties.
This is what my data looks like:
...
"offers": [
{
"school": "Foo School",
"committed": true
},
{
"school": "Bar School",
"committed": false
}
]
...
In the above example, I only want to show "Foo School".
But if both committed properties were false I want to show "Foo Schoo" and "Bar School".
Here is what I have currently, but am returning both regardless.
foreach ($object['athlete']['offers'] as $offer) {
if (isset($offer['committed']) && $offer['committed'] == 1) {
// return single school
} else {
// push into array & return?
}
}
Thank you for any suggestions!
I think this is what you were looking for, please correct me if I'm wrong. If all of them are false, then it returns all. If one or more are true, it returns the first one that's true:
<?php
$offers = array(
array("school" => "Foo School",
"committed" => true
),
array(
"school" => "Bar School",
"committed" => false
));
$fullReturn = "";
$flag = false;
foreach ($offers as $offer) {
if (isset($offer['committed']) && $offer['committed']) {
echo $offer['school'];
$flag = true;
break;
} else {
$fullReturn .= $offer['school'] . "<br />";
}
}
if (!$flag) {
echo $fullReturn;
}
?>
If you have two array and you want to check if the $haystack array have minimum $needle array's element and they match or not then you can use that function
function array_match($needle, $haystack){
$haystack = (array) $haystack;
$needle = (array) $needle;
foreach ($needle as $key => $value) {
if( trim($value) != trim($haystack[$key]) ){
return false;
}
}
return true;
}
I'm trying to convert a value from a POST array, which has letters and numbers in it automatically substituted with others upon submission, to the exact letters and numbers that are entered into the input field.
I mapped out the combinations - for instance, when you type "123456" in the input field, what you get on POST is "DTHAQO", where "D" stands for "1", "T" stands for "2", and so on. What I'm trying to do is convert that "D" to "1" automatically, and every other letter/number as well, so that the final POST value is the actual value.
What I came up with so far:
<?php
function decoder() {
$decode = $_POST['password'];
if (strpos($decode,"D") !== false) {
str_replace("D","1",$decode);
}
if (strpos($decode,"T") !== false) {
str_replace("T","2",$decode);
}
}
$decoded = decoder();
echo $decoded;
?>
However, upon echoing, nothing happens.
What am I doing wrong?
You need the function to return a value in order to use/echo it.
<?php
function decoder() {
$decode = $_POST['password'];
if (strpos($decode,"D") !== false) {
$ret_val = str_replace("D","1",$decode);
return $ret_val;
}
if (strpos($decode,"T") !== false) {
$ret_val = str_replace("T","2",$decode);
return $ret_val;
}
}
$decoded = decoder();
echo $decoded;
?>
I think this should work, but like Maximus2012 said in the comments, there are better ways to do this
$decode = "DTHAQO";//maybe your POST value
function decoder( $stringToDecode ) {
$decodeArray = array(
"D" => 1,
"T" => 2,
"H" => 3,
"A" => 4,
"Q" => 5,
"O" => 6
);
for( $i = 0; $i < strlen( $stringToDecode ); $i++ ) {
$stringToDecode[$i] = ( isset( $decodeArray[ $stringToDecode[$i] ] ) ) ? $decodeArray[ $stringToDecode[$i] ] : $stringToDecode[$i];
}
return $stringToDecode;
}
$decoded = decoder( $decode );
echo $decoded;
inside if statements replace
str_replace("D","1",$decode);
to
$decode = str_replace("D","1",$decode);
make changes for all similar to str_replace(letter, number,$decode) lines
Update:
Also, add return statement into functions
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.
}
}