Recursive function not stopping? - php

I created a recursive function to find a key-value in a multidimensional array
Function:
public function find_key_recursive($haystack, $needle) {
foreach($haystack as $key=>$value) {
if(is_array($value)){
$this->find_key_recursive($value, $needle);
} else if($key === $needle) {
return $value;
}
}
}
(Part of) Array:
$oLayoutProperties =
Array
(
[header] => Array
(
[logo_float] => left
[logo_upload] => http://placehold.it/150x100&text=afbeelding
[logo_margin_top] => 0
[searchbar_toggle] => false
[language_toggle] => false
[color] => 0
[font_size] => 12
[background_color] => 0
)
[menu] => Array
(
[menu_type] => full
[menu_align] => left
[menu_position_toggle] => false
[menuheight] => Array
(
[bar_height] => 0
)
[color] => 0
[font_size] => 12
[text_transform] => like_pagetitle
[background_color_hover] => 0
[color_hover] => 0
)
[submenu] => Array
(
[color] => 0
[font-size] => 12
[item_height] => 0
[item_width] => 0
[text-transform] => like_pagetitle
[background_color] => 0
[background_color_hover] => 0
[color_hover] => 0
)
)
I call the function as following:
$oElement_controller->find_key_recursive($oLayoutProperties, 'logo_float');
I validated (using echo's) that the key 'logo_float' indeed gets found, but I don't seem to be able to cancel the recursive function?
I tried the following:
return false;
break;
None of the above seem to work.
How do you stop a recursive function?

You can use a static variable to remember the status between multiple function calls. It makes the function remember the value of the given variable ($needle_value in this example) between multiple calls.
public function find_key_recursive($haystack, $needle){
static $needle_value = null;
if($needle_value != null){
return $needle_value;
}
foreach($haystack as $key=>$value) {
if(is_array($value)){
$this->find_key_recursive($value, $needle);
} else if($key === $needle) {
$needle_value = $value;
return $needle_value;
}
}
}
This function finally returns $needle_value, which is your desired needle in the haystack.

public function find_key_recursive($haystack, $needle) {
foreach($haystack as $key=>$value) {
if(is_array($value)){
var $found = $this->find_key_recursive($value, $needle);
if ($found){
return $found;
}
} else if($key === $needle) {
return $value;
}
}
return false;
}
I haven't touched PHP in a while, but something like this will probably work.

You can put the result in a variable passed by reference, like this:
public function find_key_recursive($haystack, $needle, &$found) {
foreach($haystack as $key => $value) {
if (is_array($value)) {
$this->find_key_recursive($value, $needle, $found);
} else if($key === $needle) {
$found = $value;
return;
}
}
}
$found = false;
$oElement_controller->find_key_recursive($oLayoutProperties, 'logo_float', $found);
if ($found !== false) {
// found!
}

Related

array_filter not working for multi dimensional array

Here is the non-functional code. It does not return anything. Not quite sure what is wrong with the syntax I am using.
function findNeedle($array, $needle) {
return array_values(array_filter($array, function($arrayValue) use($needle) { return $arrayValue['lp_url'] == $needle; } ));
}
$myarray =
0 =>
array (
'lp_url' => 'http://example.com/nx/?utm_source=aa&utm_medium=referral',
'lp_term_id' => 1435949468,
'aff_term_id' => 1445295565,
'offer_term_id' => 1445295996,
),
1 =>
array (
'lp_url' => 'http://example.org/nx/?utm_source=aa&utm_medium=referral',
'lp_term_id' => 1435949468,
'aff_term_id' => 1445295559,
'offer_term_id' => 1445295989,
),
);
$needle = 'http://example.com/nx/?utm_source=aa&utm_medium=referral';
if (is_array($myarray)) {
foreach ($myarray as $value) {
if (is_array($value))
{
$x = findNeedle($value, $needle);
}
}
Extract an array of the data for the lp_url column and check for $needle:
if(in_array($needle, array_column($myarray, 'lp_url'))) {
echo "Found";
} else {
echo "Not found";
}

Search value in array from comma separated value in PHP

I have following array
Array
(
[0] => Array
(
[data] => PHP
[attribs] => Array
(
)
[xml_base] =>
[xml_base_explicit] =>
[xml_lang] =>
)
[1] => Array
(
[data] => Wordpress
[attribs] => Array
(
)
[xml_base] =>
[xml_base_explicit] =>
[xml_lang] =>
)
)
one varialbe like $var = 'Php, Joomla';
I have tried following but not working
$key = in_multiarray('PHP', $array,"data");
function in_multiarray($elem, $array,$field)
{
$top = sizeof($array) - 1;
$bottom = 0;
while($bottom <= $top)
{
if($array[$bottom][$field] == $elem)
return true;
else
if(is_array($array[$bottom][$field]))
if(in_multiarray($elem, ($array[$bottom][$field])))
return true;
$bottom++;
}
return false;
}
so want to check if any value in $var is exists in array(case insensitive)
How can i do it without loop?
This should work for you:
(Put a few comments in the code the explain whats goning on)
<?php
//Array to search in
$array = array(
array(
"data" => "PHP",
"attribs" => array(),
"xml_base" => "",
"xml_base_explicit" => "",
"xml_lang" => ""
),
array(
"data" => "Wordpress",
"attribs" => array(),
"xml_base" => "",
"xml_base_explicit" => "",
"xml_lang" => "Joomla"
)
);
//Values to search
$var = "Php, Joomla";
//trim and strtolower all search values and put them in a array
$search = array_map(function($value) {
return trim(strtolower($value));
}, explode(",", $var));
//function to put all non array values into lowercase
function tolower($value) {
if(is_array($value))
return array_map("tolower", $value);
else
return strtolower($value);
}
//Search needle in haystack
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
//Search ever value in array
foreach($search as $value) {
if(in_array_r($value, array_map("tolower", array_values($array))))
echo $value . " found<br />";
}
?>
Output:
php found
joomla found
to my understanding , you are trying to pass the string ex : 'php' and the key : 'data' of the element .
so your key can hold a single value or an array .
$key = in_multiarray("php", $array,"data");
var_dump($key);
function in_multiarray($elem, $array,$field)
{
$top = sizeof($array) - 1;
$bottom = 0;
while($bottom <= $top)
{
if(is_array($array[$bottom][$field]))
{
foreach($array[$bottom][$field] as $value)
{
if(strtolower(trim($value)) == strtolower(trim($elem)))
{
return true;
}
}
}
else if(strtolower(trim($array[$bottom][$field])) == strtolower(trim($elem)))
{
return true;
}
$bottom++;
}
return false;
}

Check if all values of keys of multidimentionnal array are numeric?

i'm gona crazy, debuting in php..
I need to check if key value of an multidimentionnal array are all numeric..
a print_r() of my $values_arr give that:
Array ( [coco] => Array ( [0] => 18 [1] => 99 ) [chanel] => 150
I need to check if 18 and 99 and 150 are numeric, i will don't know what will in the array , and this array will not more 2 dimention.
I tryed many things, the last one..:
foreach ( $values_arr as $foo=>$bar ) {
if( !in_array( $foo, $_fields_arr ) || !is_numeric($bar ) ) {
echo "NOTGOOD";
}
}
****UPDATE****
new test :Here because chanel isnot int , this exemple should be echo "not goud",
but its not the case..
$_fields_arr = array('coco','chanel','other');
$ary = array(
'coco' => array(18, 99),
'chanel' => 'yu'
);
function allIntValues($o)
{
if (is_int($o)) return true;
if (is_array($o)){
foreach ($o as $k => $v) {
if (!is_int($v)) return false;
}
}
return true;
}
foreach ($ary as $k => $v) {
if (!in_array($k, $_fields_arr) || !#allIntValues($v)){
echo "notgood";
}
else echo "good";
}
thanks for any help,
regards
Update:
$ary = Array(
'coco' => array(18, 99),
'chanel' => 150
);
$_fields_arr = array('coco', 'chanel');
function allIntValues($o)
{
if (is_int($o)) return true;
if (is_array($o)){
foreach ($o as $k => $v) {
if (!is_int($v)) return false;
}
}
return true;
}
foreach ($ary as $k => $v) {
if (in_array($k, $_fields_arr) && #allIntValues($v)){
// $ary[$k] is no good
}
}
Assuming you want to test if all values are numeric (despite how deep the value's nested):
function is_numeric_array($ary)
{
foreach ($ary as $k => $v)
{
if (is_array($v))
{
if (!is_numeric_array($v))
return false;
}
else if (!is_numeric($v))
return false;
}
return true;
}
That will (recursively) check the array and make sure every value is numeric within the array.
array(1,2,3) // true
array('foo','bar','baz') // false ('foo', 'bar' & 'baz')
array(1,2,array(3,4)) // true
array(array(1,'foo'),2,3) // false (foo)
array("1,", "2.0", "+0123.45e6") // true
You are using the value instead of the key:
if( !in_array( $bar, $_fields_arr ) || !is_numeric($foo ) ) {

PHP find value in multidimensional / nested array

I've trawled the site and the net and have tried various recursive functions etc to no avail, so I'm hoping someone here can point out where I'm going wrong :)
I have an array named $meetingArray with the following values;
Array (
[0] => Array (
[Meet_ID] => 9313
[Meet_Name] => 456136
[Meet_CallInNumber] =>
[Meet_AttendeeCode] =>
[Meet_Password] =>
[Meet_ScheduledDateTime] => 2011-07-18 16:00:00
[Meet_ModeratorCode] =>
[Meet_RequireRegistration] => 0
[Meet_CurrentUsers] => 0
)
[1] => Array (
[Meet_ID] => 9314
[Meet_Name] => 456120
[Meet_CallInNumber] =>
[Meet_AttendeeCode] =>
[Meet_Password] =>
[Meet_ScheduledDateTime] => 2011-07-18 16:00:00
[Meet_ModeratorCode] =>
[Meet_RequireRegistration] => 0
[Meet_CurrentUsers] => 0
)
)
I also have a variable named $meetID.
I want to know if the value in $meetID appears in [Meet_Name] within the array and simply evaluate this true or false.
Any help very much appreciated before I shoot myself :)
function multi_in_array($needle, $haystack, $key) {
foreach ($haystack as $h) {
if (array_key_exists($key, $h) && $h[$key]==$needle) {
return true;
}
}
return false;
}
if (multi_in_array($meetID, $meetingArray, 'Meet_Name')) {
//...
}
I am unsure what you mean by
$meetID appears in [Meet_Name]
but simply substitute the $h[$key]==$needle condition with something that meets your needs.
For single-dimensional arrays you can use array_search(). This can be adapted for multi-dimensional arrays like so:
function array_search_recursive($needle, $haystack, $strict=false, $stack=array()) {
$results = array();
foreach($haystack as $key=>$value) {
if(($strict && $needle === $value) || (!$strict && $needle == $value)) {
$results[] = array_merge($stack, array($key));
}
if(is_array($value) && count($value) != 0) {
$results = array_merge($results, array_search_recursive($needle, $value, $strict, array_merge($stack, array($key))));
}
}
return($results);
}
Write a method something like this:
function valInArr($array, $field, $value) {
foreach ($array as $id => $nestedArray) {
if (strpos($value,$nestedArray[$field])) return $id;
//if ($nestedArray[$field] === $value) return $id; // use this line if you want the values to be identical
}
return false;
}
$meetID = 1234;
$x = valInArr($array, "Meet_Name", $meetID);
if ($x) print_r($array[$x]);
This function will evaluate true if the record is found in the array and also enable you to quickly access the specific nested array matching that ID.

Return true/false on searching multidimensional array

I have the following multidimensional $array:
Array
(
[0] => Array
(
[domain] => example.tld
[type] => 2
)
[1] => Array
(
[domain] => other.tld
[type] => 2
)
[2] => Array
(
[domain] => blaah.tld
[type] => 2
)
)
I simply want to recursively search all the arrays on both key and value, and return true if the key/value was found or false if nothing was found.
Expected output:
search_multi_array($array, 'domain', 'other.tld'); // Will return true
search_multi_array($array, 'type', 'other.tld'); // Will return false
search_multi_array($array, 'domain', 'google.com'); // Will return false
I've figured out a ugly-ugly method to search against the domain against all keys with this function:
function search_multi_array($search_value, $the_array) {
if (is_array($the_array)) {
foreach ($the_array as $key => $value) {
$result = search_multi_array($search_value, $value);
if (is_array($result)) {
return true;
} elseif ($result == true) {
$return[] = $key;
return $return;
}
}
return false;
} else {
if ($search_value == $the_array) {
return true;
}
else
return false;
}
}
Can anyone do better and match both against the key and value in a more elegant way?
If it doesn't go beyond those 2 levels, flipping keys/merging makes life a lot more pleasant:
<?php
$data = array
(
'0' => array
(
'domain' => 'example.tld',
'type' => 2
),
'1' => array
(
'domain' => 'other.tld',
'type' => 2,
),
'2' => array
(
'domain' => 'blaah.tld',
'type' => 2
)
);
$altered = call_user_func_array('array_merge_recursive',$data);
var_dump($altered);
var_dump(in_array('other.tld',$altered['domain']));
var_dump(in_array('other.tld',$altered['type']));
var_dump(in_array('google.com',$altered['domain']));
To go beyond 2nd level, we have to loop once through all the nodes:
$option2 = array();
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($data)) as $key => $value){
$option2[$key][] = $value;
}
var_dump($option2);
One way is to create a reverse mapping from [domain] => [indices] and from [type] => [indices]. It's probably not going to save you much unless you do lots of searches.
(hint: you probably want to wrap it into a class to prevent inconsistencies in the mappings)
also, anytime you see something like this:
if ($search_value == $the_array) {
return true;
} else {
return false;
}
you can always turn it into:
return $search_value == $the_array;
function search_mutli_array($SearchKey, $SearchValue, $Haystack)
{
$Result = false;
if (is_array($Haystack))
{
foreach ($Haystack as $Key => $Value)
{
if (is_array($Value))
{
if (search_mutli_array($SearchKey, $SearchValue, $Value))
{
$Result = true;
break;
}
}
else if ($SearchKey == $Key && $SearchValue == $Value)
{
$Result = true;
break;
}
}
}
return $Result;
}

Categories