Getting a section of a multidimensional array php - php

I have a multidimensional array below. And I am trying to get certain part of the array based on a value that is passed into the function. But for some reason it returns false even though the path matches, it only return something if /test is used but if I type /hello the if fails and it returns false.
here is the array:
Array
(
[0] => Array
(
[name] => test_route
[path] => /test
[controller] => TestController
[action] => indexAction
)
[1] => Array
(
[name] => hello_route
[path] => /hello
[controller] => HelloController
[action] => helloAction
)
)
and here is the method:
public function getRoute($path = "", $name = "")
{
foreach($this->routes as $key => $val)
{
if($val['path'] === $path || $val['name'] === $name)
{
return $this->routes[$key];
}
else
{
return false;
}
}
}

Just modifying on the code you provided , may be you should try something like this :
public function getRoute($path = "", $name = "")
{
foreach($this->routes as $key => $val)
{
if($val['path'] === $path || $val['name'] === $name)
{
return $this->routes[$key];
}
}
return false;
}

Your method exists after examining the first element. Remove the else block and put the return false outside the loop.
foreach($this->routes as $key => $val)
{
if($val['path'] === $path || $val['name'] === $name)
{
return $this->routes[$key];
}
}
return false;

I'm not sure why /test even works. You're dealing with a multidimensional array. foreach does not do deep searches. You're going to have to modify your code to this:
public function getRoute($path = "", $name = "")
{
foreach($this->routes as $route) {
foreach($route as $key => $val)
{
if($val['path'] === $path || $val['name'] === $name)
{
return $route[$key];
}
}
}
return false;
}

Related

Filter multilevel array with multiple values

I'm trying to solve an issue where I have an multilevel array that needs to be filtered with user controlled filters.
Example of the array
[1] => Array
(
[objectID] => 5038
[Data] => Array
(
[originalId] => 6
)
[titles] => InfoType Object
(
[_] => string
[language] => eng
)
)
The filters would be then language and objectID, for example.
Anything that doesn't meet the criteria will have to be excluded. Sounds perfectly find if that would be a SQL query, but it's not. The API returns a string that cannot be controlled and it's in a form of an array. Have to work with what you have.
The idea came up to write a function that would prepare an if-statement. Problem is that you can't do just that
foreach ($cache as $listing) {
foreach ($filters as $filter_param => $filter_value) {
if ($query) $output[] = $listing;
}
}
In this case the $query would be equal to something like this:
$listing["titles"]["language"] =="eng" && $listing["objectID"] =="5038"
I'm pretty sure there's an easier way that wouldn't actually be bad. Really stuck with this one.
function isGood($what, $filters) {
foreach ($filters as $key => $value) {
if (is_array($value)) {
if (isGood($what[$key], $value) === false) {
return false;
}
} else {
if ($what[$key] != $value) {
return false;
}
}
}
return true;
}
foreach($cache as $listing) {
if (isGood($listing, $filters)) {
$output[] = $listing;
}
}

Recursive function not stopping?

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

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

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