I have this small search function in my page;
$searchWord is the word that I need to look for in my array.
The array looks a bit like this:
stdClass Object (
[ActionScopeId] => 181365
[DateChanged] => 0001-01-01T00:00:00
[DateCreated] => 2013-08-20T13:59:33.053
[Description] => Snelheid test
[MessageCode] => C0000448220
)
stdClass Object (
[ActionScopeId] => 181364
[DateChanged] => 0001-01-01T00:00:00
[DateCreated] => 2013-08-14T10:08:50.707
[Description] => Test
[MessageCode] => C0000448219
)
Now, for example; I want to look for the word 'Test'. When it's found, I want to print the ActionScopeId and DateCreated with it.
This is my code:
$roc = array('relation' => $_SESSION['username']);
$rocresponse = $wcfclient->ReadOpenCalls($roc);
foreach ($rocresponse->ReadOpenCallsResult as $key => $value){
foreach ($value as $key1 => $value1){
if (array_search($searchWord,$value1)){
echo $value1->ActionScopeId;
}
}
}
But, the result I get is always empty. What am I doing wrong?
I fixed it, when trying to search into an object you can use this function:
function in_object($val, $obj){
if($val == ""){
trigger_error("in_object expects parameter 1 must not empty", E_USER_WARNING);
return false;
}
if(!is_object($obj)){
$obj = (object)$obj;
}
foreach($obj as $key => $value){
if(!is_object($value) && !is_array($value)){
if($value == $val){
return true;
}
}else{
return in_object($val, $value);
}
}
return false;
}
And then look for it in this way:
if (in_object($searchWord,$value)){
I fixed this by using this function:
function in_object($val, $obj){
if($val == ""){
trigger_error("in_object expects parameter 1 must not empty", E_USER_WARNING);
return false;
}
if(!is_object($obj)){
$obj = (object)$obj;
}
foreach($obj as $key => $value){
if(!is_object($value) && !is_array($value)){
if($value == $val){
return true;
}
}else{
return in_object($val, $value);
}
}
return false;
And then look for it in this way:
if (in_object($searchWord,$value)){}
Related
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";
}
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!
}
Currently stuck trying to get the last part working, wanting to get all array keys returned where the value exists.
Test data
$testArr = array(
'id' => '249653315914',
'title' => 'testing',
'description' => 'testing',
'usernames' => array('jake', 'liam', 'john'),
'masterNames' => array('jake'),
'data' => array(
'aliases' => array(
'jake'
)
)
);
Method
recursive_search('jake', $testArr);
function recursive_search($needle, $haystack, $child = false) {
$values = array();
foreach($haystack as $key => $value) {
$current_key = $key;
if($needle === $value OR (is_array($value) && $children = recursive_search($needle, $value, true) !== false)) {
if($child) {
if($needle == $value) {
return true;
}
echo "children: $child, current_key: $current_key ";
return $current_key;
}
echo "current_key: $current_key, key: $key <br>";
$values[] = $current_key;
}
}
if(!empty($values)) {
return $values;
}
return false;
}
Output
current_key: usernames, key: usernames
current_key: masterNames, key: masterNames
children: 1, current_key: aliases current_key: data, key: data
array (size=3)
0 => string 'usernames' (length=5)
1 => string 'masterNames' (length=8)
2 => string 'data' (length=4)
Expected
array(
'usernames',
'masterNames',
'data' => array('aliases')
)
I'm losing track on the $child part I think, somewhere I should be returning something and assigning it but I think I've looked at this to long and overlooking the obvious.
Any help is awesome.
$testArr = array(
'id' => '249653315914',
'title' => 'jake',
'description' => 'testing',
'usernames' => array('jake', 'liam', 'john'),
'masterNames' => array('jake'),
'data' => array(
'aliases' => array(
'jake'
),
'aliases2' => array('level3' => array('jake'))
)
);
function recursive_search($needle, $haystack) {
$return = array();
if (is_array($haystack))
foreach($haystack as $key => $value)
{
if (is_array($value))
{
$child = recursive_search($needle, $value);
if (is_array($child) && !empty($child))
$return = array_merge($return, array($key => $child));
elseif ($child) $return[] = $key;
}
elseif ($value === $needle)
if (is_integer($key))
return true;
else
$return[] = $key;
}
elseif ($haystack === $needle)
return true;
return $return;
}
Output
Array
(
[0] => title
[1] => usernames
[2] => masterNames
[data] => Array
(
[0] => aliases
[aliases2] => Array
(
[0] => level3
)
)
)
Testing is needed, no warranty that it will work in all cases. Also, in the cases like this array('level3' => array('jake'), 'jake'), it will not go deeper to level3 and so on, as 'jake' is present in the original array. Please mention if that is not a desired behavior.
Edit by Bankzilla: To work with objects
function recursive_search($needle, $haystack) {
$return = array();
if (is_array($haystack) || is_object($haystack)) {
foreach($haystack as $key => $value) {
if (is_array($value) || is_object($value)) {
$child = recursive_search($needle, $value);
if ((is_array($child) || is_object($child)) && !empty($child)) {
$return = array_merge($return, array($key => $child));
} elseif ($child) {
$return[] = $key;
}
}
elseif ($value === $needle) {
if (is_integer($key)) {
return true;
} else {
$return[] = $key;
}
}
}
} elseif ($haystack === $needle) {
return true;
}
return $return;
}
the things I thought you did wrong was checking for if current $value is an array and doing a recursive search on it, while doing nothing with the return value of it (which should be the array either false ) , here I used a more step by step approach (well at least I thought so )
this works for a "tree with more branches"
EDIT
function recursive_search($needle, $haystack) {
$values = array();
foreach($haystack as $key => $value) {
if(is_array($value)) {
$children = $this->recursive_search($needle, $value);
if($children !== false){
if(!is_bool($children) and !empty($children)){
$key = array($key => $children);
}
$values[] = $key;
}
} else if(strcmp($needle, $value) == 0 ){
if(is_int($key))
return true;
else
$vaues[] = $key;
}
}
if(!empty($values)) {
return $values;
}
return false;
}
got rid of the "0"s in the array, thx Cheery for the hint (from his response)
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 ) ) {
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;
}