PHP - Search String And Remove Element in Json - php

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

Related

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

Decode API response in PHP from Google Maps

I'm struggling to get the "Adams County" from "administrative_area_level_2" type
from this api response
http://maps.googleapis.com/maps/api/geocode/json?latlng=39.76144296429947,-104.8011589050293&sensor=false .
I simply need to output the county based on the latitude and longitude.
$query = #unserialize(file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng=39.76144296429947,-104.8011589050293&sensor=false'));
echo 'Hello visitor from '.$query["response"];
This is what I have for now. Thank you.
You will need to use a recursive search and keep track of the previous found item in the result array.
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=39.76144296429947,-104.8011589050293&sensor=false';
$query = #json_decode(file_get_contents($url),true);
$address_components = $query['results'][0]['address_components'];
array_walk_recursive( $address_components,
function($item, $key) use(&$prev_item, &$stop){
if($item == 'administrative_area_level_2'){
$stop = true;
}
else {
if(!$stop)
$prev_item = $item;
}
});
var_dump($prev_item);
Use json_decode instead of unserialize, as the response is in JSON format.
Then just iterate the items in a loop or two, for example:
$url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=39.76144296429947,-104.8011589050293&sensor=false'; $response = json_decode(file_get_contents($url), true);
if (empty($response['results'])) {
// handle error
}
$long_name = null;
foreach ($response['results'] as $r) {
if (empty($r['address_components']) || empty($r['types']))
continue;
if (array_search('administrative_area_level_2', $r['types']) === false)
continue;
foreach ($r['address_components'] as $ac) {
if (array_search('administrative_area_level_2', $ac['types']) !== false) {
$long_name = $ac['long_name'];
break;
}
}
}
echo $long_name;
Output
Adams County

Function with loop calling same function in PHP

I'm having a trouble. I was trying to make it work for a long time, so I decided to ask for help here.
I have an with some arrays inside it:
$myarray = [
['string1','string2'],
['string3','string4'],
['string5',['string6','string7','string99']],
['string8','string9']
];
I am making a function that search for a s
function searchArray($array,$chave,$id) {
foreach ($array as $key) {
if (is_array($key)) {
if (($key[0] == $chave) && ($key[1] == $id)) {
break;
}
else {
searchArray($key,$chave,$id);
}
}
}
return $key;
}
$result = searchArray($myarray,'string6','string7');
print_r($result);
It was supposed to print ['string6','string7','string99']]
But it it printing the last "key" of the array: ['string8','string9']
The break is not working. After the break, it continue checking the next arrays.
with these modification it returns the expected values:
<?php
$myarray = [
['string1','string2'],
['string3','string4'],
['string5',['string6','string7','string99']],
['string8','string9']
];
function searchArray($array,$chave,$id) {
foreach ($array as $key) {
if (is_array($key)) {
if (($key[0] == $chave) && ($key[1] == $id)) {
return $key;
} else {
$res = searchArray($key,$chave,$id);
if($res !== false) {
return $res;
}
}
}
}
return false;
}
$result = searchArray($myarray,'string6','string7');
print_r($result);
the failure was to break on success. That makes no sense.
You need to return the value on success. If no success return false. Imagine it may happen that the searched values will not been found so it should return false.

Data Not Being Parsed Correctly

I have a simple data format that goes as follows:
stuff/stuff/stuff
An example would be:
data/test/hello/hello2
In order to retrieve a certain piece of data, one would use my parser, which tries to do the following:
In data/test/hello/hello2
You want to retrieve the data under data/test (which is hello). My parser's code is below:
function getData($data, $pattern)
{
$info = false;
$dataLineArray = explode("\n", $data);
foreach($dataLineArray as &$line)
{
if (strpos($line,$pattern) !== false) {
$lineArray = explode("/", $line);
$patternArray = explode("/", $pattern);
$iteration = 0;
foreach($lineArray as &$lineData)
{
if($patternArray[$iteration] == $lineData)
{
$iteration++;
}
else
{
$info = $lineData;
}
}
}
}
return $info;
}
However, it always seems to return the last item, which in this case is hello2:
echo getData("data/test/hello/hello2", "data/test");
Gives Me;
hello2
What am I doing wrong?
If you want the first element after the pattern, put break in the loop:
foreach($lineArray as $lineData)
{
if($patternArray[$iteration] == $lineData)
{
$iteration++;
}
elseif ($iteration == count($patternArray))
{
$info = $lineData;
break;
}
}
I also check $iteration == count($patternArray) so that it won't return intermediate elements, e.g.
/data/foo/test/hello/hello2
will return hello rather than foo.
P.S. There doesn't seem to be any reason to use references instead of ordinary variables in your loops, since you never assign to the reference variables.

PHP parsing multidimensional json array of any depth based on key

I have an json array like given below, what I want is to
parse through the array and get a value for corresponding
key .Eg SubAdministrativeAreaName .I could have parsed it
like .
["AddressDetails"]['Country']['AdministrativeArea'] ['SubAdministrativeArea']['SubAdministrativeAreaName']
but the structure of array is not fixed , it may contain some other
keys within which "SubAdmininstrativeArea" may be enclosed .
What I want is a php function that will search for a particular key
name through multidimensional json array of any depth .
Any help would be appreciated .
"AddressDetails": {
"Accuracy": 6,
"Country": {
"AdministrativeArea": {
"AdministrativeAreaName": "Maharashtra",
"SubAdministrativeArea": {
"SubAdministrativeAreaName": "Parbhani",
"Thoroughfare": {
"ThoroughfareName": "SH217"
}
}
},
"CountryName": "India",
"CountryNameCode": "IN"
}
}
OK, different answer based on comment below:
function array_key_search_deep($needle, $haystack) {
$value = NULL;
if(isset($haystack[$needle])) {
$value = $haystack[$needle];
} else {
foreach($haystack as $node) {
if(is_array($node)) {
$value = array_key_search_deep($needle, $node);
if(!is_null($value)) {
break;
}
}
}
}
return $val;
}
Old Answer
This will allow you to traverse an unknown path in any array tree:
$path = array('AddressDetails', 'Country', 'AdministrativeArea', 'SubAdministrativeArea', 'SubAdministrativeAreaName');
$node = $json_object;
foreach($path as $path_index) {
if(isset($node[$path_index])) {
$node = $node[$path_index];
} else {
$node = NULL;
}
}
echo($node);
Thanks guys , what I made was a a solution like this
I finally found a simple solution myself
For eg) To get "ThoroughfareName" make a call
recursive_array_search($json_array,'ThoroughfareName') ;
function recursive_array_search($arr,$jackpot)
{
foreach ($arr as $key => $value)
{
if(is_array($value))
{
$val=recursive_array_search($value,$jackpot) ;
return $val;
}
else
{
if($key==$jackpot)
return $value;
}
}
}
You could use JSONPath (XPath for JSON)
http://goessner.net/articles/JsonPath/
(with for instance the expression "$..SubAdministrativeAreaName")
EDIT: Haven't tested it, not sure how reliable it is.

Categories