note 117117 deleted from function.array-filter by cmb
| From: | cmb@php.net | Date: | Sun, 06 Oct 2019 07:58:18 +0000 |
| Subject: | note 117117 deleted from function.array-filter by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212490@lists.php.net to get a copy of this message | ||
Note Submitter: manuelworks at gmail dot com
----
I needed to get the complete array element of a multilevel array where the values of some elements
where 'x' or 'y'. Kind of a WHERE AND in a MySQL Query..
SO if you need to filter an array where 'X' = Y and 'a' = b, here you go.
<?php
/*
* getArrayElement() by @MmO12
*
* SELECT an element of an $array...
* *$array = array( 0 => array('index1' => 'a', 'index2' =>
'b', 'value' => 'hello'),
1 => array('index1' => 'a', 'index2' =>
'c', 'value' => 'bye'));
*
* WHERE its $indexs values are equal to...
* * $indexs = array('index1' => 'a', 'index2'=>'b');
*/
function getArrayElement($array, $indexs, $justvalsplease = false){
$newarray = false;
//verificamos el array
if(is_array($array) && count($array)>0){
//verify indexs and get # of indexs
if(is_array($indexs) && count($indexs)>0) $ninds = count($indexs);
else return false;
//search for coincidences
foreach(array_keys($array) as $key){
//index value coincidence counter.
$count = 0;
//for each index we search
foreach($indexs as $indx => $val){
//if index value is equal then counts
if($array[$key][$indx] == $val){
$count++;
}
}
//if indexes match, we get the array elements :)
if($count == $ninds){
//if you only need the vals of the first coincidence
//witch was my case by the way...
if($justvalsplease) return $array[$key];
else $newarray[$key] = $array[$key];
}
}
}
return $newarray;
}
?>
/*******
Example
********/
<?php
//array
$array = array( 0 => array('index1' => 'a', 'index2' =>
'b', 'value' => 'hello'),
1 => array('index1' => 'a', 'index2' =>
'c', 'value' => 'bye'),
2 => array('index1' => 'b', 'index2' =>
'a', 'value' => 'hi'));
//indexes
$indexs = array('index1' => 'a', 'index2'=>'b');
//aaand we get the element we want.
$element = getArrayElement($array, $indexs);
print_r($element);
/***prints ***/
Array
(
[0] => Array
(
[index1] => a
[index2] => b
[value] => hello
)
)?>
IF you want only the array inside the elements just set $justvalsplease true like this
<?php
$element = getArrayElement($array, $indexs,true);
?>
And you will get just the element content
<?php
Array
(
[index1] => a
[index2] => b
[value] => hello
)
?>