Page 1 of 1

Array key searching for record

Posted: Mon Oct 20, 2008 5:23 am
by superfury
Made a function that may come in handy when trying to get a part of an array when you know the key and it's value.
Use this for getting the (sub)array where that key containing that value is in:

Code: Select all

<?php
/*
parsearray: searches $thearray for the first key where $identifier has the value $objectvalue and returns that record
example:
when: $thearray = array('sub1'=array('name'='test1','value'='0'),'sub2'=array('name'='test2','value'='1'));
$theresult = parsearray($thearray,'name',"test1");
 
now $theresult is:
$theresult['found'] = TRUE;
$theresult['data'] =  array('name'='test1','value'='0')
and when the parameter containing $objectvalue becomes "test2":
$theresult['found'] = TRUE;
$theresult['data'] = array('name'='test2','value'='1')
and when $identifier doesn't exists or when it is not a valid value,
  or when the key $identifier with value $objectvalue doesn't appear in the array then:
$theresult['found'] = FALSE;
and
isset($theresult['data'])==FALSE
 
 
 
Commented php commands (print) are for debugging only.
*/
 
function parsearray($thearray,$identifier,$objectvalue,$currentdepth = 0)
{
$result = array();
$result['found'] = FALSE;
if ($currentdepth==0)
{
//print("<br>Start searching for key: \"$identifier\"=\"$objectvalue\"");
}
//print("<br>Parsing array @ depth $currentdepth");
//When it's an array, parse it.
if (is_array($thearray))
{
foreach ($thearray as $key=>$value)
{
if (is_array($value) && $result['found']!=TRUE)
{
$subresult = parsearray($value,$identifier,$objectvalue,$currentdepth + 1);
if ($subresult['found']==TRUE)
{
$thedepth = $currentdepth + 1;
//print("<br><font color=red>Received found from layer #$thedepth!</font>");
$result = $subresult;
return $subresult;
}
}
if ($key==$identifier && $value==$objectvalue && $keyfound==FALSE)
{
//print("<br><font color=red>FOUND!!!</font>");
$result['data'] = $thearray;
$result['found'] = TRUE;
return $result;
}
}
}
return $result;
}
 
?>
Any comments?

Re: Array key searching for record

Posted: Mon Oct 20, 2008 6:37 am
by onion2k
I can't help thinking this is the sort of thing that array_map would be better for.

Code: Select all

<?php
 
    $thearray = array('sub1'=>array('name'=>'test1','value'=>'0'),'sub2'=>array('name'=>'test2','value'=>'1'));
    
    $search = array_map("map_name", $thearray, array_keys($thearray), array_fill(0, count($thearray), "name"), array_fill(0, count($thearray), "test1"));
    
    function map_name($i, $key, $field, $search) {
        
        if ($i[$field]==$search) { return $key; }
    
    }
    
    print_r($search);
That's a very quick and dirty approach. I'm sure that could be improved upon.