I have a multidimensional array like this:
$a['bla1']['blub1']="test123";
$a['bla1']['blub2']="test1234";
$a['bla1']['blub3']="test12345";
$a['bla2']['blub1']="test123456";
$a['bla2']['blub2']="test12344e45";
$a['bla2']['blub3']="test12345335";
How to search by value and get back bla1 or bla2? I don't need the subkey, only the key.
try this:
function searcharray($a, $value)
{
foreach($a as $key1 => $keyid)
{
foreach($keyid as $key => $keyid2)
{
if ( $keyid2 === $value )
return $key.','.$key1;
}
}
return false;
}
This function recursively searches an array to any depth and returns the main key under which $needle is found:
function get_main_key($arr, $needle) {
$out = FALSE;
foreach ($arr as $key => $value) {
if ($value == $needle) {
$out = $key;
} elseif (is_array($value)) {
$ret = get_main_key($value, $needle);
$out = ( ! empty($ret)) ? $key : $out;
}
}
return $out;
}
Related
I am very new to the PHP, i want to check the value is present inside the associative array,please help me to acheive this thing.
public $array=[
'id','name',
'value.details'=>['type'=>'myFunction']
];
foreach($array as $key=>$condition){
if(in_array('myFunction',$array)){
//My logic
}
}
if you know the keys:
if($array['value.details']['type'] === 'myFunction') { }
if you walk through your array:
foreach($array as $key=>$val) {
if(is_array($val) && in_array('myFunction', $val)) {
//
}
}
Your array is mix of string and array, you might also wanna check the array inside your array.
$array=[
'id','name',
'value.details'=>['type'=>'myFunction']
];
$query = 'myFunction';
$isPresent = false;
foreach ($array as $data) {
if (gettype($data) === "array") {
foreach ($data as $val) {
if ($val === $query) {
$isPresent = true;
continue;
}
}
} else {
if ($query === $data) {
$isPresent = true;
continue;
}
}
}
hi i have an array of about 20/30 items big.
i need to have it loop threw the array and echo out only the items with the text p1 in them.
the array looks like so
"lolly","lollyp1","top","topp1","bum","bump1","gee","geep1"
and so on
i have tried to use something like this
foreach ($arr as $value) {
$needle = htmlspecialchars($_GET["usr"]);
$ret = array_keys(array_filter($arr, function($var) use ($needle){
return strpos($var, $needle) !== false;
}));
but all this gives me is a blank page or 1s
how can i have it echo out the items with p1 in them ?
Try This:
$needle = htmlspecialchars($_GET["usr"]);
$rtnArray = array();
foreach ($arr as $value) {
$rtnArray = strpos($value,$needle);
};
return $rtnArray;
If your trying to write directly to the page the lose the $rtnarray and echo:
$needle = htmlspecialchars($_GET["usr"]);
foreach ($arr as $value) {
echo strpos($value,$needle);
};
To only show ones with 'p1' then filter:
$needle = htmlspecialchars($_GET["usr"]);
foreach ($arr as $value) {
$temp = strpos($value,$needle);
if($temp > 1){
echo $value;
}
};
Using a direct loop with string-comparison would be a simple way to go here:
$needle = $_GET['usr'];
$matches = array();
foreach ($arr as $key => $value) {
if (strpos($value, $needle) !== false) {
$matches[] = $key;
}
}
The use of array_filter() in your post should work, pending the version of PHP you're using. Try updating to use a separate / defined function:
function find_needle($var) {
global $needle;
return strpos($var, $needle) !== false;
}
$ret = array_keys(array_filter($arr, 'find_needle'));
Codepad Example of the second sample
I have a array of val which has dynamic strings with underscores. Plus I have a variable $key which contains an integer. I need to match $key with each $val (values before underscore).
I did the following way:
<?php
$key = 2; //always a dynamic number
$val = array('3_33', '2_55'); //always a dynamic string with underscore
if(in_array($key, $val)) {
echo 'Yes';
}
else
{
echo 'No';
}
?>
Though this code works fine, I want to know if its a correct way or suggest some better alternative.
use this function for regex match from php.net
function in_array_match($regex, $array) {
if (!is_array($array))
trigger_error('Argument 2 must be array');
foreach ($array as $v) {
$match = preg_match($regex, $v);
if ($match === 1) {
return true;
}
}
return false;
}
and then change your code to use this function like this:
$key = 2; //always a dynamic number
$val = array('3_33', '2_55'); //always a dynamic string with underscore
if(in_array_match($key."_*", $val)) {
echo 'Yes';
}
else
{
echo 'No';
}
This should work :
foreach( $val as $v )
{
if( strpos( $v , $key .'_' ) === true )
{
echo 'yes';
}
else {
echo 'no';
}
}
you can use this
function arraySearch($find_me,$array){
$array2 =array();
foreach ($array as $value) {
$val = explode('_',$value);
$array2[] =$val[0];
}
$Key = array_search($find_me, $array2);
$Zero = in_array($find_me, $array2);
if($Key == NULL && !$Zero){
return false;
}
return $Key;
}
$key = 2; //always a dynamic number
$val = array('3_33', '2_55'); //always a dynamic string with underscore
$inarray = false;
foreach($val as $v){
$arr = explode("_", $val);
$inarray = $inarray || $arr[0] == $key
}
echo $inarray?"Yes":"No";
The given format is quite unpractically.
$array2 = array_reduce ($array, function (array $result, $item) {
list($key, $value) = explode('_', $item);
$result[$key] = $value;
return $result;
}, array());
Now you can the existence of your key just with isset($array2[$myKey]);. I assume you will find this format later in your execution useful too.
Hi i have a multidimensional associative array:
$array= array(
'Book1' => array('http://www.google.com', '45' ),
'Book2' => array('http://www.yahoo.com', '46', )
)
I need to be able to search $array on 'BookX' and then return the contents of 'BookX'.
Ive tried:
function array_searcher($needles, $array)
{
foreach ($needles as $needle) {
foreach ($array as $key )
{
if ($key == $needle)
{
echo $key;
}
}
}
}
with the search
$needles = array('Book1' , 'Book2' );
But this doesnt return anything
I might be misunderstanding, but this just sounds like the accessor. If not, could you clarify?
$array= array(
'Book1' => array('http://www.google.com', '45' ),
'Book2' => array('http://www.yahoo.com', '46', )
);
echo $array['Book1'];
EDIT: I did misunderstand your goal. I do have a comment on doing the two foreach loops. While this does work, when you have a very large haystack array, performance suffers. I would recommend using isset() for testing if a needle exists in the haystack array.
I modified the function to return an array of the found results to remove any performance hits from outputing to stdout. I ran the following performance test and while it might not do the same search over and over, it points out the inefficiency of doing two foreach loops when your array(s) are large:
function array_searcher($needles, $array) {
$result = array();
foreach ($needles as $needle) {
foreach ($array as $key => $value) {
if ($key == $needle) {
$result[$key] = $value;
}
}
}
return $result;
}
function array_searcher2($needles, $array) {
$result = array();
foreach ($needles as $needle) {
if (isset($array[$needle])) {
$result[$needle] = $array[$needle];
}
}
return $result;
}
// generate large haystack array
$array = array();
for($i = 1; $i < 10000; $i++){
$array['Book'.$i] = array('http://www.google.com', $i+20);
}
$needles = array('Book1', 'Book2');
$start = microtime(true);
for ($i = 0; $i < 1000; $i++) {
array_searcher($needles, $array);
}
echo (microtime(true) - $start)."\n";
// 14.2093660831
$start = microtime(true);
for ($i = 0; $i < 1000; $i++) {
array_searcher2($needles, $array);
}
echo (microtime(true) - $start)."\n";
// 0.00858187675476
If you want to search using the keys, you should access it as a key => value pair.
If you don't it only retrieves the value.
function array_searcher($needles, $array)
{
foreach ($needles as $needle)
{
foreach ($array as $key => $value)
{
if ($key == $needle)
{
echo $key;
}
}
}
}
What's the best way to remove the parent of a matched key in an Multidimensional Array? For example, let's assume we have the following array and I want to find "[text] = a" and then delete its parent array [0]...
(array) Array
(
[0] => Array
(
[text] => a
[height] => 30
)
[1] => Array
(
[text] => k
[height] => 30
)
)
Here’s the obvious:
foreach ($array as $key => $item) {
if ($item['text'] === 'a') {
unset($array[$key]);
}
}
using array_filter:
function filter_callback($v) {
return !isset($v['text']) || $v['text'] !== 'a';
}
$array = array_filter($array, 'filter_callback');
this will only leave 'parent elements' in the array where text != a, therefore deleting those where text equals a
The inner arrays don't maintain any reference to their "parent" arrays, so you'd have to write a function to manually track this. Something like this might work:
function searchAndDestroy(&$arr, $needle) {
foreach ($arr as &$item) {
if (is_array($item)) {
if (searchAndDestroy($item, $needle)) {
return true;
}
} else if ($item === $needle) {
$item = null;
return true;
}
}
}
Note that this is designed to work at any level of nesting, not just two dimensions, so it might be a bit of overkill if you only need it for situations like in your example.
A simple and safe solution(I'd not remove/unset elements from an array I'm looping through) could be:
$new_array = array();
foreach($array as $item)
{
if($item['text'] != "a")
{
$new_array[] = $item;
}
}
My implementation:
function searchAndDestroy(&$a, $key, $val){
foreach($a as $k => &$v){
if(is_array($v)){
$r = searchAndDestroy(&$v, $key, $val);
if($r){
unset($a[$k]);
}
}elseif($key == $k && $val == $v){
return true;
}
}
return false;
}
searchAndDestroy($arr, 'text', 'a');
To test it:
<pre><?php
function searchAndDestroy(&$a, $key, $val){
foreach($a as $k => &$v){
if(is_array($v)){
$r = searchAndDestroy(&$v, $key, $val);
if($r){
unset($a[$k]);
}
}elseif($key == $k && $val == $v){
return true;
}
}
return false;
}
$arr = array(array('text'=>'a','height'=>'30'),array('text'=>'k','height'=>array('text'=>'a','height'=>'20')));
var_dump($arr);
searchAndDestroy($arr, 'text', 'a');
var_dump($arr);
?></pre>
This function does it recursively.