I am very new to the PHP, i want to check the value is present inside the associative array,please help me to acheive this thing.
public $array=[
'id','name',
'value.details'=>['type'=>'myFunction']
];
foreach($array as $key=>$condition){
if(in_array('myFunction',$array)){
//My logic
}
}
if you know the keys:
if($array['value.details']['type'] === 'myFunction') { }
if you walk through your array:
foreach($array as $key=>$val) {
if(is_array($val) && in_array('myFunction', $val)) {
//
}
}
Your array is mix of string and array, you might also wanna check the array inside your array.
$array=[
'id','name',
'value.details'=>['type'=>'myFunction']
];
$query = 'myFunction';
$isPresent = false;
foreach ($array as $data) {
if (gettype($data) === "array") {
foreach ($data as $val) {
if ($val === $query) {
$isPresent = true;
continue;
}
}
} else {
if ($query === $data) {
$isPresent = true;
continue;
}
}
}
Related
I'm trying to flatten a multidimensional array that was returned by json_decode() but I'm having issues. I've some research but all of the solutions seem to be skipping over some of my data. If I run this and compare the echo'd data to var_dump() I'm definitely not getting everything and I'm not sure why.
Here is what I have so far:
<?php
function array_flatten($array) {
if (!is_array($array)) {
return false;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, array_flatten($value));
} else {
$result[$key] = $value;
}
}
return $result;
}
for ($x = 1; $x <= 1; $x++) {
$response = file_get_contents('https://seeclickfix.com/api/v2/issues?page='.$x
.'&per_page=1');
// Decode the JSON and convert it into an associative array.
$jsonDecoded = json_decode($response, true);
$flat = array_flatten($jsonDecoded['issues']);
foreach($flat as $item) {
echo $item;
echo "<br>";
}
}
?>
array_merge will overwrite values with the same key, as you can see in the documentation. E.g. in the link you posted, you will lose some urls. You could fix that by create unique keys in the flattened array. For example by passing a prefix to your function:
function array_flatten($array, $prefix = '') {
if (!is_array($array)) {
return false;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, array_flatten($value, $prefix.'_'.$key));
} else {
$result[$prefix.'_'.$key] = $value;
}
}
return $result;
}
I have a multidimensional array $array["A"]["B"]["C"]["D"]. The list is longer.
Is there a wildcard that I can use to get ["D"] value in let say ["B"] array?
Something like this, $array["A"]["B"][*]["D"] ?
or $array[*]["B"][*]["D"] ?
Example, I would like to get all prices that were bought on February regardless of the year.
$array[2013][2][23]["ItemName"]["ItemPrice"] .....
If this would work, it would be really wonderful
$array[*][2][*][*]["ItemPrice"]..
any idea?
You could do multiple foreach to loop though every nested array that you want to loop though.
foreach ($array as $a) {
foreach ($a["B"] as $c) {
foreach ($c as $d) {
// Do something with $d
}
}
}
This would be $array[*]["B"][*][*]
Edit: You could combine my suggestion with a while loop.
$innerArray = $array;
while (true) {
foreach ($array as $key => $value) {
if ($key == "D") {
// Do something with this value
} else if (is_array($value)) {
$innerArray = $value;
} else {
break;
}
}
}
Thanks to #Sepehr-Farshid it just crossed my mind that I can use recursive function (Something that I haven't use for quiet a while. So here a example.
$newarray = array();
$tempArray = $oldarray;
$levels[] = 1;
$keys[] = 2;
$levels[] = 4;
$keys[] = "ItemPrice";
$lastLevel =4;
recurArray($tempArray, 0);
function recurArray($array, $level)
{
foreach($array as $key => $value) {
if(array_search($level, $GLOBALS["levels"]) {
$tempKey = array_search($level, $GLOBALS["levels"];
if($key == $GLOBALS["keys"][$tempKey] {
if($level == $GLOBALS["lastLevel"]) $GLOBALS["newarray"] = $value;
else recurArray($value, $level + 1);
}
else { return; }
}
else { recurArray($value, $level + 1); }
}
}
this might not be the optimum way, but it will work and can be refined. :D
I'm trying to validate a string to an array of numbers. If the string only contains numbers then the function should validate, but in_array isn't working, any suggestions?
$list = array(0,1,2,3,4,5,6,7,8,9);
$word = 'word';
$split = str_split($word);
foreach ($split as $s) {
if (!in_array($s, $list)) {
print 'asdf';
}
}
here is the class:
class Validate_Rule_Whitelist {
public function validate($data, $whitelist) {
if (!Validate_Rule_Type_Character::getInstance()->validate($data)) {
return false;
}
$invalids = array();
$data_array = str_split($data);
foreach ($data_array as $k => $char) {
if (!in_array($char, $whitelist)) {
$invalids[] = 'Invalid character at position '.$k.'.';
}
}
if (!empty($invalids)) {
$message = implode(' ', $invalids);
return $message;
}
return true;
}
}
in_array comparison with loosely typed values is somewhat strange. What would work in your case is:
$list = array('0','1','2','3','4','5','6','7','8','9');
$word = 'word';
$split = str_split($word);
foreach ($split as $s) {
if (!in_array($s, $list, true)) {
print 'asdf';
}
}
This compares strings with strings and results in no surprises.
But, as noted in the comments already, this is quite wrong way to do things and it is much better to use filter_var() or regular expressions** to achieve what you're trying.
it's ugly as sin but it works, no elegant solution here, just a double loop, if you see any problems please let me know
$match = array();
foreach ($data_array as $k => $char) {
foreach ($whitelist as $w) {
if (!isset($match[$k])) {
if ($char === $w) {
$match[$k] = true;
}
}
}
if (!isset($match[$k]) || $match[$k] !== true) {
$invalids[$k] = 'Invalid character at position '.$k.'.';
}
}
Something along the lines of this should work:
<?php
$validate_me = '123xyz';
if(preg_match("/[^0-9]/", $validate_me, $matches))
print "non-digit detected";
?>
update: add the $type = gettype ... settype($char, $type) to allow === to function correctly when checking for integers
foreach ($data_array as $k => $char) {
foreach ($whitelist as $w) {
if (!isset($match[$k])) {
$type = gettype($w);
if (gettype($char) !== $type) {
settype($char, $type);
}
if ($char === $w) {
$match[$k] = true;
}
}
}
...
I wasn't so clear in my first question, so i deleted it and here is a reformulation;
I have those arrays:
$open = array(array("FAI1","34"),array("FAI2","34"),array("FAI3","34"));
$click = array(array("FAI2","52"),array("FAI1","68"),array("FAI3","99"));
$unsubscribe = array(array("FAI2","103"),array("FAI3","67"),array("FAI1","102"));
$def_sent = array(array("FAI1","34",24),array("FAI2","34",23),array("FAI3","34",27));
$SB = array(array("FAI2","103"),array("FAI3","67"),array("FAI1","102"));
$HB = array(array("FAI2","103"),array("FAI3","67"),array("FAI1","102"));
I searched for a function to merge them and get a result like this:
$result = array(array("FAI1",34,68,102,34,24,102,102)
,array("FAI2","34",23.....),
array("FAI3","34",27....));
and to do this, i used the function, in the php online documentation, and this is the function
function array_merge_recursive() {
$arrays = func_get_args();
$base = array_shift($arrays);
foreach ($arrays as $array) {
reset($base);
while (list($key, $value) = #each($array)) {
if (is_array($value) && #is_array($base[$key])) {
$base[$key] = array_merge_recursive($base[$key], $value);
} else {
$base[$key] = $value;
}
}
}
return $base;
}
But instead of getting the result above i got this:
FAI1|34
FAI2|34
FAI3|34
FAI2|52
FAI1|68
FAI3|99
...
So i need some help to reformulate this function to get the expected result.
Try this function:
function array_merge_rec() {
$arrays = func_get_args();
$result = array();
foreach ($arrays as $arg) {
if (is_array($arg)) {
foreach ($arg as $item) {
if (!isset($result[$item[0]])) {
$result[$item[0]] = $item;
} else {
$result[$item[0]][] = $item[1];
}
}
} else {
echo "$arg skippend because it isn't array\n";
}
}
return array_values($result);
}
Does it help?
I have a multidimensional array like this:
$a['bla1']['blub1']="test123";
$a['bla1']['blub2']="test1234";
$a['bla1']['blub3']="test12345";
$a['bla2']['blub1']="test123456";
$a['bla2']['blub2']="test12344e45";
$a['bla2']['blub3']="test12345335";
How to search by value and get back bla1 or bla2? I don't need the subkey, only the key.
try this:
function searcharray($a, $value)
{
foreach($a as $key1 => $keyid)
{
foreach($keyid as $key => $keyid2)
{
if ( $keyid2 === $value )
return $key.','.$key1;
}
}
return false;
}
This function recursively searches an array to any depth and returns the main key under which $needle is found:
function get_main_key($arr, $needle) {
$out = FALSE;
foreach ($arr as $key => $value) {
if ($value == $needle) {
$out = $key;
} elseif (is_array($value)) {
$ret = get_main_key($value, $needle);
$out = ( ! empty($ret)) ? $key : $out;
}
}
return $out;
}