How can I check if a key/value pair exists in php? - php

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

Related

Find a specific word in an object using strpos in php

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

Search in array DNS entry

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

PHP - Find previous value in multidimensional array

I have this array:
$test = array( "a" => "b",
"c" => array("foo" => "bar",
"3" => "4",
),
"e" => "f",);
I want to create a function that finds the previous value in this array, given a certain value, for example find("bar", $test); should return "b".
This is what I got:
function find($needle, $array, $parent = NULL)
{
//moves the pointer until it reaches the desired value
while (current($array) != $needle){
//if current value is an array, apply this function recursively
if (is_array(current($array))){
$subarray = current($array);
//passes the previous parent array
find($needle, $subarray, prev($array));
}
//once it reaches the end of the array, end the execution
if(next($array) == FALSE){
return;
}
}
//once the pointer points to $needle, run find_prev()
find_prev(prev($array), $parent);
}
function find_prev($prev, $parent = NULL)
{
// in case there is no previous value in array and there is a superior level
if (!$prev && $parent) {
find_prev($parent);
return;
}
// in case previous value is an array
// find last value of that array
if (is_array($prev) && $prev){
find_prev(end($prev), $parent));
return;
} else {
$GLOBALS['pre'] = $prev;
}
}
For pedagogical reasons and since I have devoted some time to this function, it would be great if you could provide any hints about why this isn't working rather than any other simpler solution that you might have.
You have an infinite loop. Your algorithm is a bit complicated for what you want to do. Maybe you should just keep the previous value in a variable and return it when you find the $needle. Here is the corresponding code. I tried to not modify your code as much as I could:
function find($needle, $array, $lastValue = NULL)
{
$previousValue = null;
//moves the pointer until it reaches the desired value
while (current($array) != FALSE) {
$value = current($array);
//if current value is an array, apply this function recursively
if (is_array($value)) {
$subarray = $value;
//passes the previous value as the last value for the embedded array
$value = find($needle, $subarray, $previousValue);
if ($value !== NULL) {
return $value;
}
} else if ($value === $needle) {
//returns the previous value of the current array
if ($previousValue !== NULL) {
return $previousValue;
//returns the last checked value of the parent array
} else if ($lastValue !== NULL) {
return $lastValue;
} else {
return;
}
} else {
$previousValue = $value;
}
next($array);
}
}
$test = array(
"a" => "b",
"c" => array(
"foo" => "bar",
"3" => "4"
),
"e" => "f"
);
$result = find("bar", $test);
if ($result === null) {
print('no previous value');
} else {
$GLOBALS['pre'] = $result;
print($GLOBALS['pre']);
}
You may try TDD to code this kind of algorithm. It could help you.
The function find() calls itself recursively for sub-arrays but it doesn't check if the inner call found something or not and keep searching. This is why the first call to find_prev() runs with $test['b'] as its first parameter (prev() of the last element in $test). You expect it to run with $test['a'].

How to Display Element of Array that has specific value/character?

I Have A json Array from hxxp://best1st.info/Moviedb/json.php?m=tt2015381&o=json
Here is sample of the array output :
. and so on
.
.
[STORYLINE] => On planet Earth in 1988, young Peter Quill ( ) sits in the waiting room of a hospital...
[ALSO_KNOWN_AS] => Array
(
[0] => Guardianes de la galaxia = Argentina
[1] => Qalaktikanin Mühafizeçileri = Azerbaijan
[2] => Пазителите на Галактиката = Bulgaria (Bulgarian title)
[3] => Guardiões da Galáxia = Brazil
)
[RELEASE_DATES] => Array
(
.
.
. and so on
I want to check if in "ALSO_KNOWN_AS" Element, have "Argentina" word , If "ALSO_KNOWN_AS" Element have the "Argentina" word, then display it (the value).
I have try to do it (search with google and here on stackoverflow), but seem my code dont work, Can some one here help me to fix it , here is my code
$url = 'http://best1st.info/Moviedb/json.php?m=tt2015381&o=json';
$newdata = json_decode(file_get_contents($url));
$alsoKnownAs = $newdata->ALSO_KNOWN_AS;
if (in_array('Argentina', $alsoKnownAs)) {
echo "Match found";
// echo the-array-value
}
else
{
echo "Match not found";
return false;
}
Thanks You
try this
$url = 'http://best1st.info/Moviedb/json.php?m=tt2015381&o=json';
$newdata = json_decode(file_get_contents($url));
$found = false;
foreach($newdata->ALSO_KNOWN_AS as $value)
{
if(strpos($value, "Argentina") !==false)
{
echo $value;
echo "<br/>";
$found = true;
}
}
if($found===false)
{
echo "Not found";
}
function searchArray($search, $array)
{
foreach($array as $key => $value)
{
if (stristr($value, $search))
{
return true;
}
}
return false;
}
Here in the above function first argument is the string you like to search and second argument is the array and it will iterate through entire array with the function stristr whose work is to return portion on found else false.
Note: if you need case sensitive search instead of stristr use strstr or strchr
if (searchArray('Argentina', $alsoKnownAs)) {
echo "Match found";
// echo the-array-value
}
else
{
echo "Match not found";
return false;
}
Your entries in the ALSO_KNOWN_AS array are not single words like "Argentina" but rather comparisons with country names and other text. This is why in_array() won't find it. in_array() needs precise matches. So you have to check all items.
I suggest you replace the if statement by a foreach loop:
...
...
$found = false;
foreach ($alsoKnownAs as $item) {
if (strpos($item, 'Argentina') !== false) {
$found = true;
break;
}
}
if (!$found) {
echo "Match not found";
return false;
}
Hope this helps :-)

Checking conditions in multidimensional array

I have an array like this:
$_SESSION['food'] = array(
array(
"name" => "apple",
"shape" => "round",
"color" => "red"
),
array(
"name" => "banana",
"shape" => "long",
"color" => "yellow"
)
);
I want to make a statement that checks whether any particular combination of values exists within any of the second level arrays above.
So, basically:
if NAME=APPLE and COLOR=RED in FOOD // returns true
if NAME=BANANA and COLOR=GREEN in FOOD // returns false
if NAME=APPLE and SHAPE=LONG in FOOD // returns false
How would I construct the if() statements above (just one statement as an example would be sufficient)? I am really stumped here.
I suspect it has something to do with running an in_array() within a foreach(), but I am not sure of the exact syntax.
Thanks a lot for any help.
Something like:
foreach($_SESSION['food'] as $fruit) {
if($fruit['name'] == 'apple' && $fruit['color'] == 'red') {
return true;
}
}
You have to loop over all the arrays and you could use array_intersect_assoc for comparison:
function contains($haystack, $needle) {
$needle_length = count($needle);
foreach($haystack as $sub) {
if(is_array($sub)
&& count(array_intersect_assoc($needle, $sub)) === $needle_length) {
return true;
}
}
return false;
}
and call it with:
$red_apple = array('name'=>'apple','color'=>'red');
if(contains($_SESSION['food'], $red_apple)) {
// something
}
With this you can easily check for any combination of values for any array containing arrays.
function existsInArray($name, $color){
foreach($_SESSION['food'] as $foodItem){
if($foodItem['name'] ==$name && $foodItem['color'] == $color){
return true;
}
}
return false;
}
hope that helps!

Categories