php里如何把 数组里的php数组去除指定元素素给取出来

php中怎么让数组中的2个元素位置互换_php吧_百度贴吧
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&签到排名:今日本吧第个签到,本吧因你更精彩,明天继续来努力!
本吧签到人数:0成为超级会员,使用一键签到本月漏签0次!成为超级会员,赠送8张补签卡连续签到:天&&累计签到:天超级会员单次开通12个月以上,赠送连续签到卡3张
关注:139,666贴子:
php中怎么让数组中的2个元素位置互换收藏
例如arr=array(1,2);变成arr=array(2,1);最好写一个函式;
兄弟连php教育,php,0基础先入学后付款,跟大咖高洛峰学php,学不会才是奇迹!本月php免费试学7天还赠送图书《跟兄弟连学PHP》精要版.兄弟连php培训,信赖之选!
php内置了超多的数组函数。简单倒排可以用这个:array_reverse仔细看手机有更多排序用的函数
直接在下面替换也行啊
$赋值[0]=2 $赋值[1]=1 .或者就是2楼的
function change($p_arr,$key1,$key2){
if(isset($p_arr[$key1]) && isset($p_arr[$key2])){
$temp1=$p_arr[$key1];
$temp2=$p_arr[$key2];
$p_arr[$key1]=$temp2;
$p_arr[$key2]=$temp1;
return $p_}这样?
$arr=array(1,2);$arr[0]=$arr[0] ^ $arr[1];$arr[1]=$arr[0] ^ $arr[1];$arr[0]=$arr[0] ^ $arr[1];位运算,速度几乎是最快的;
$a=$arr[1];$arr[1]=$arr[2];$arr[2]=$a;
function change($arr){
$a=$arr[1];
$arr[1]=$arr[2];
$arr[2]=$a;}
谢谢各位了
登录百度帐号推荐应用php中单个删除数组中指定的值用array_百度文库
两大类热门资源免费畅读
续费一年阅读会员,立省24元!
php中单个删除数组中指定的值用array
阅读已结束,下载文档到电脑
想免费下载本文?
定制HR最喜欢的简历
你可能喜欢2017年3月 PHP大版内专家分月排行榜第三2016年12月 PHP大版内专家分月排行榜第三2016年11月 PHP大版内专家分月排行榜第三2014年10月 PHP大版内专家分月排行榜第三2014年8月 PHP大版内专家分月排行榜第三2014年3月 PHP大版内专家分月排行榜第三2014年1月 PHP大版内专家分月排行榜第三2012年8月 PHP大版内专家分月排行榜第三2012年2月 PHP大版内专家分月排行榜第三2012年1月 PHP大版内专家分月排行榜第三2011年12月 PHP大版内专家分月排行榜第三2011年11月 PHP大版内专家分月排行榜第三2011年6月 PHP大版内专家分月排行榜第三
本帖子已过去太久远了,不再提供回复功能。PHP 在数组中搜索给定的值,如果成功则返回相应的键名
在线手册:&
在线手册:&
Unfortunately&a&lot&of&the&very&well&written&solutions&to&the&multidimensional&array&search&problem&did&not&work&for&me,&so&I&wrote&this:&?php&&&&function&recursive_array_key_search&($needle,&array&$haystack)&&&&{&&&&&&&&foreach(is_array($needle)&?&recursive_array_key_search(array_shift($needle),&$haystack)&:&$haystack&as&$key=&$value)&&&&&&&&{&&&&&&&&&&&&if((is_array($needle)&&&&reset($needle)&===&$key)&||&$needle&===&$key)&&&&&&&&&&&&{&&&&&&&&&&&&&&&&return&$value;&&&&&&&&&&&&}&&&&&&&&&&&&if&(is_array($value)&&&&$value&=&recursive_array_key_search($needle,&$value))&&&&&&&&&&&&{&&&&&&&&&&&&&&&&return&$value;&&&&&&&&&&&&}&&&&&&&&}&&&&}?&The&advantage&of&this&script&is&that&you&can&specify&one&or&more&keys&to&search&on&in&an&array&which&passes&down&the&array&structure.Take&this&array:Array(&&&&[id]&=&&709&&&&[type]&=&&post&&&&[slug]&=&&derek&&&&[url]&=&&&&&&[tags]&=&&Array&&&&&&&&(&&&&&&&&&&&&[one]&=&&Array&&&&&&&&&&&&&&&&(&&&&&&&&&&&&&&&&&&&&[id]&=&&167&&&&&&&&&&&&&&&&&&&&[slug]&=&&bob&&&&&&&&&&&&&&&&&&&&[title]&=&&Whateverville&&&&&&&&&&&&&&&&&&&&[description]&=&&&&&&&&&&&&&&&&&&&&&&[post_count]&=&&1&&&&&&&&&&&&&&&&)&&&&&&&&&&&&[two]&=&&Array&&&&&&&&&&&&&&&&(&&&&&&&&&&&&&&&&&&&&[id]&=&&168&&&&&&&&&&&&&&&&&&&&[slug]&=&&mary&&&&&&&&&&&&&&&&&&&&[title]&=&&Single&&&&&&&&&&&&&&&&&&&&[description]&=&&&&&&&&&&&&&&&&&&&&&&[post_count]&=&&1&&&&&&&&&&&&&&&&)&&&&&&&&))Then&using&the&function&you&can&return&either&a&single&variable:&?phprecursive_array_key_search('url',&$haystack);&//&returns&''recursive_array_key_search('slug',&$haystack);&//&returns&the&first&instance&of&slug:&'bob'?&Or,&you&can&specify&two&or&more&keys&to&match&in&sequence,&like&so:&?phprecursive_array_key_search(array('two',&'slug'),&$haystack)&//&returns&'mary'?&I&hope&that's&useful&to&someone!
I&made&a&function&what&determine&highest&key&and/or&value&&in&array.&?phpfunction&highest($array){$previous_key=0;$prev_value=0;foreach($array&as&$key&=&&$value){$act=($value&=$prev_value)?&$key&:&$previous_key;$prev_value&=&$array[$act];$previous_key&=&$act;}return&$act;//&or&u&can&return&a&given&array&or&value//&return&array($act&=&&$array[$act]);}$ar=array(0,1,21,3,800,5,6,7,4);echo&highest($ar);&//&output&key&4?&
And&if&you&want&to&find&the&entire&series&of&keys&to&get&to&a&value,&try&this.
&?php
function&recursive_array_search($needle,$haystack)&{
&&&&foreach($haystack&as&$key=&$value)&{
&&&&&&&&$current_key=$key;
&&&&&&&&if&(is_array($value))&$val&=&recursive_array_search($needle,$value);
&&&&&&&&if($needle===$value&OR&($val&!=&false&and&$val&!=&NULL))&{
&&&&&&&&&&&&if($val==NULL)&return&array($current_key);
&&&&&&&&&&&&return&array_merge(array($current_key),&$val);
&&&&&&&&}
&&&&}
&&&&return&false;
}
?&
A&recursive&search&function&that&returns&all&the&keys&it&finds.&?phppublic&static&function&arr_search(array&$array,&$needle,&$break_at_first&=&false){&&&&$ret&=&array();&&&&&&&&foreach&($array&as&$key&=&&$val)&&&&{&&&&&&&&if&(&!&is_array($val))&&&&&&&&{&&&&&&&&&&&&if&($needle&==&$val)&&&&&&&&&&&&{&&&&&&&&&&&&&&&&$ret[]&=&$key;&&&&&&&&&&&&&&&&if&($break_at_first)&&&&&&&&&&&&&&&&{&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&}&&&&&&&&&&&&}&&&&&&&&}&&&&&&&&else&&&&&&&&{&&&&&&&&&&&&$sub_ret&=&arr_search($val,&$needle,&$break_at_first);&&&&&&&&&&&&&&&&&&&&&&&&if&(count($sub_ret)&&&0)&&&&&&&&&&&&{&&&&&&&&&&&&&&&&$ret[]&=&$key;&&&&&&&&&&&&&&&&$ret&=&array_merge($ret,&$sub_ret);&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&if&($break_at_first)&&&&&&&&&&&&&&&&{&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&}&&&&&&&&&&&&}&&&&&&&&}&&&&}&&&&&&&&return&$ret;}//&Example$arr&=&array(&&&&'o',&&&&'a'&=&&array(&&&&&&&&'b'&=&&'c',&&&&&&&&'d'&=&&'e',&&&&),&&&&'x'&=&&'y',&&&&'c',&&&&'k'&=&&array(&&&&&&&&'c',&&&&&&&&'l'&=&&'m',&&&&&&&&'n'&=&&'c',&&&&),&&&&'z',);arr_search($arr,&'c',&false);/*Returns:Array(&&&&[0]&=&&a&&&&[1]&=&&b&&&&[2]&=&&1&&&&[3]&=&&k&&&&[4]&=&&0&&&&[5]&=&&n)*/arr_search($arr,&'c',&true);/*Returns:Array(&&&&[0]&=&&a&&&&[1]&=&&b)*/?&Some&practical&usage&example:&?php$ip_arr&=&array(&&&&'main'&=&&array(&&&&&&&&'head'&=&&'1.2.3.4',&&&&&&&&'it'&=&&'1.2.3.5',&&&&&&&&'hr'&=&&'1.2.3.6',&&&&&&&&'sales'&=&&'1.2.3.7',&&&&),&&&&'other_office'&=&&array(&&&&&&&&'sales'&=&&'2.3.4.5',&&&&&&&&'marketing'&=&&'2.3.4.6',&&&&));$found&=&arr_search($ip_arr,&$_SERVER['REMOTE_ADDR']);if&(in_array('sales',&$found))&//&Show&sthif&(in_array('it',&$found))&//&Debugif&(in_array('head',&$found))&//&Tell&the&boss&everything&is&just&fine!?&
hey&i&have&a&easy&multidimensional&array&search&function&
&?php
function&search($array,&$key,&$value)
{
&&&&$results&=&array();
&&&&if&(is_array($array))
&&&&{
&&&&&&&&if&(isset($array[$key])&&&&$array[$key]&==&$value)
&&&&&&&&&&&&$results[]&=&$array;
&&&&&&&&foreach&($array&as&$subarray)
&&&&&&&&&&&&$results&=&array_merge($results,&search($subarray,&$key,&$value));
&&&&}
&&&&return&$results;
}
?&
Here&is&a&recursive&search&for&a&"key"&(not&value)&in&nested&array/object.Returns:&array&with&"values"&for&the&searched&"key"&?php//&recursive&search&for&key&in&nested&array,&also&search&in&objects!!//&returns:&array&with&"values"&for&the&searched&"key"function&search_nested_arrays($array,&$key){&&&&if(is_object($array))&&&&&&&&$array&=&(array)$array;&&&&&&&&//&search&for&the&key&&&&$result&=&array();&&&&foreach&($array&as&$k&=&&$value)&{&&&&&&&&&if(is_array($value)&||&is_object($value)){&&&&&&&&&&&&$r&=&search_nested_arrays($value,&$key);&&&&&&&&&&&&if(!is_null($r))&&&&&&&&&&&&&&&&array_push($result,$r);&&&&&&&&}&&&&}&&&&&&&&if(array_key_exists($key,&$array))&&&&&&&&array_push($result,$array[$key]);&&&&&&&&&&&&if(count($result)&&&0){&&&&&&&&//&resolve&nested&arrays&&&&&&&&$result_plain&=&array();&&&&&&&&foreach&($result&as&$k&=&&$value)&{&&&&&&&&&&&&&if(is_array($value))&&&&&&&&&&&&&&&&$result_plain&=&array_merge($result_plain,$value);&&&&&&&&&&&&else&&&&&&&&&&&&&&&&array_push($result_plain,$value);&&&&&&&&}&&&&&&&&return&$result_plain;&&&&}&&&&return&NULL;}?&Example:--------&?php$example_array&=&array("a"=&"A1",&"b"=&(object)&array("a"=&"A2",&"b"=&"B",&"C"));$result_array&=&search_nested_arrays($example_array,&"a");?&Result:-------Array&(&[0]&=&&A2&[1]&=&&A1&)
I&used&this&function&to&delete&some&values&from&an&array.If&the&3rd&parameter&is&set&to&false,&only&the&first&occurrence&is&deleted.&It&outputs&a&clearly&sorted&array.&?phpfunction&array_delete&($needle,&$haystack,&$all&=&true)&{&&&&$haystack_updated&=&$haystack;&&&&foreach&($haystack&as&$num&=&&$val)&{&&&&&&&&if&($val&==&$needle&&&&$all)&{&&&&&&&&&&&&unset&($haystack_updated&[$num]);&&&&&&&&}&&&&&&&&elseif&($val&==&$needle&&&&$all&===&false&&&&!isset&($done))&{&&&&&&&&&&&&$done&=&true;&&&&&&&&&&&&unset&($haystack_updated&[$num]);&&&&&&&&}&&&&}&&&&$haystack_updated&=&array_values&($haystack_updated);&&&&return&$haystack_updated;}?&
I&have&just&tried&to&add&the&function&of&recursive&Array&Search&in&order&to&return&all&finding&keys&in&an&array&instead&of&the&first&matching&result&index,&and&further&expanded&search&to&contain&needle&instead&of&exactly&matching:&
&?php
function&recursiveArraySearchAll($haystack,&$needle,&$index&=&null)&
{&
&&&&$aIt&&&&&=&new&RecursiveArrayIterator($haystack);&
&&&&$it&&&&=&new&RecursiveIteratorIterator($aIt);&
&&&&$resultkeys;
&&&&&&&&&&&&&&&&&&&&&&&&
&&&&while($it-&valid())&{&&&&&&&&
&&&&if&(((isset($index)&AND&($it-&key()&==&$index))&OR&(!isset($index)))&AND&(strpos($it-&current(),&$needle)!==false))&{&//$it-&current()&==&$needle
&&&&$resultkeys[]=$aIt-&key();&//return&$aIt-&key();&
&&&&}&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&$it-&next();&
&&&&}&
&&&&return&$resultkeys;&&//&return&all&finding&in&an&array
&&&&&&&&&&&&&&&&&&&&&&&&
}&;
?&
To&use&the&function&on&your&array&search:
&?php
print_r(recursiveArraySearchAll($your-array,'your-needle-to&match','your-array-index-to-search')&);
?&
Simple!&and&Enjoy!
I&had&an&array&of&arrays&and&needed&to&find&the&key&of&an&element&by&comparing&actual&reference.Beware&that&even&with&strict&equality&(===)&php&will&equate&arrays&via&their&elements&recursively,&not&by&a&simple&internal&pointer&check&as&with&class&objects.&The&===&can&be&slow&for&massive&arrays&and&also&crash&if&they&contain&circular&references.This&function&performs&reference&sniffing&in&order&to&return&the&key&for&an&element&that&is&exactly&a&reference&of&needle.&?php&function&array_ref_search(&$v,&array&&$s){&&&&if(is_object($v)){&return&array_search($v,&$s,&true);&}&&&&foreach($s&as&$rK&=&&&$rV)&&&&{&//&reference&sniff&&&&&&&&$tV&=&$v;&&&&&&&&if(&($rV&===&($v&=&1))&&&&($rV&===&($v&=&0))&){&&&&&&&&$v&=&$tV;&return&$rK;&}&&&&&&&&$v&=&$tV;&&&&}&&&&return&false;&//&use&null&for&php&&&4.2.0}$list&&&=&array();$list['A']&=&&$valA;&$list['B']&=&&$valB;$valA&=&1;&$valB&=&1;echo&'array_ref_search:&',&array_ref_search($valB,&$list),&'&/br&';&//&key&'B'echo&'array_search:&&&&&',&array_search($valB,&$list,&true),&'&/br&';&//&key&'A'$valA&=&array(1,2,3);&$valB&=&array(1,2,3);echo&'array_ref_search:&',&array_ref_search($valB,&$list),&'&/br&';&//&key&'B'echo&'array_search:&&&&&',&array_search($valB,&$list,&true),&'&/br&';&//&key&'A'&because&($valA&===&$valB)&is&true&by&elements$valB[]&=&&$valB;&//&circular&referenceecho&'array_ref_search:&',&array_ref_search($valB,&$list),&'&/br&';&//&key&'B'echo&'array_search:&&&&&',&array_search($valB,&$list,&true),&'&/br&';&//&crash&because&($valB&===&$valB)&causes&infinite&loop?&
I&built&a&function&to&find&the&numeric&index&of&a&key&in&an&array.&?php/**&*&Array&key&index&*&@author&Nate&Ferrero&*/function&array_key_index(&$arr,&$key)&{&&&&$i&=&0;&&&&foreach(array_keys($arr)&as&$k)&{&&&&&&&&if($k&==&$key)&return&$i;&&&&&&&&$i++;&&&&}}
Some&thing&that&I&wrote&from&a&while,&for&what&ever&usefull&purposeThis&retrieves&recursively&a&value&from&an&array&using&a&path-like&notation.&&&&with:&&&&&&$delimiter&&&&&&&&&path&delimiter&&&&&$strict&&&&&&&&&&&&&&if&false,&the&search&will&allow&gaps&between&path's&components&&&&&&&&&&?phpfunction&path_through_array($path,&$array,&$delimiter&=&'.',&$strict&=&false){&&$path_token&=&explode($delimiter,&$path);&&$head&=&array_shift($path_token);&&if&(isset($array[$head])&&&&(0&==&count($path_token)))&&{&&&&return&$array[$head];&&}&&else&if&(isset($array[$head]))&&{&&&&return&path_through_array(implode($delimiter,&$path_token),&$array[$head],&$delimiter,&$strict);&&}&&else&if&($strict&==&true)&&{&&&&return&false;&&}&&foreach&($array&as&$key=&$value)&&{&&&&if&(is_array($value))&&&&{&&&&&&$found&=&path_through_array($path,&$value,&$delimiter,&$strict);&&&&&&if(false&!=&$found)&&&&&&{&&&&&&&&return&$found;&&&&&&}&&&&}&&}&&return&false;}//use:$array1&=&array('path'&=&&array('to'&=&&array('get'&=&&array('something'&=&&'bar')),&'somethingelse'),&'foo'&=&&'anotherthing');$val1&=&path_through_array('path.to.get.something',&$array1);&&&&&&&&&&&&&&&&&&&&&&&&&//&=&&will&return&:&'bar'$val2&=&path_through_array('path.to.get',&$array1);&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&//&=&&will&return&:&array('something'=&'bar')$val3&=&path_through_array('path/to/get/something',&$array1,&'/');&&&&&&&&&&&&&&&&&&//&=&&will&return&:&'bar'$val4&=&path_through_array('path.to.something',&$array1);&&&&&&&&&&&&&&&&&&&&&&&&&&&&//&=&&will&return&:&'bar'$val5&=&path_through_array('path.to.something',&$array1,&'.',&true);&&&&&&&&&&&&&&&//&=&&will&return&:&false
This&is&a&multidimensional&recursive&find&function&:&?phpfunction&GetArrKey(&$findArr,&$key_arr,&$depth=0&){&&&&&&&&if(&count($key_arr)&&=&$depth&||&!array_key_exists($key_arr[$depth],&$findArr)&)&&&&&&&&&&&&&&&&return&NULL;&&&&&&&&else&if(&count($key_arr)&==&$depth+1&)&&&&&&&&&&&&&&&&return&$findArr[$key_arr[$depth]];&&&&&&&&&&&&&&&&return&self::GetArrKey(&$findArr[$key_arr[$depth]],&$key_arr,&$depth+1&);}?&Using&:&?php&&&&&&&&$findArray&=&array(&"first_dim"&=&&array(&"first_dim_in_1"&=&&array(&"first_dim_in_1_val_1",&"first_dim_in_1_val_2",&"first_dim_in_1_val_3"&),&"first_dim_in_2"&=&&array(&"first_dim_in_2_val_1",&"first_dim_in_2_val_2",&"first_dim_in_2_val_3"&)&),&"second_dim"&=&&array(&"second_dim_in"&=&&"test",&"second_dim_in_val_1"));&&&&&&&&var_dump(&GetArrKey(&$findArray,&array(&"first_dim",&"first_dim_in_2"&)&)&);&&&&&&&&/*&&&&&&&&&&&&Prints&:&&&&&&&&&&&&array(&"first_dim_in_2_val_1",&"first_dim_in_2_val_2",&"first_dim_in_2_val_3"&)&&&&&&&&*/&&&&&&&&//----------------------------------------------------//&&&&&&&&var_dump(GetArrKey(&$findArray,&array(&"first_dim",&"first_dim_in_2",&0&)&)&);&&&&&&&&/*&&&&&&&&&&&&Prints&:&&&&&&&&&&&&string(20)&=&&"first_dim_in_2_val_1"&&&&&&&&*/&&&&&&&&//----------------------------------------------------//&&&&&&&&var_dump(GetArrKey(&$findArray,&array(&"second_dim",&0&)&)&);&&&&&&&&/*&&&&&&&&&&&&Prints&:&&&&&&&&&&&&string(4)&=&&"test"&&&&&&&&*/&&&&&&&&//----------------------------------------------------//&&&&&&&&var_dump(GetArrKey(&$findArray,&array(&"second_dim",&0&)&)&);&&&&&&&&/*&&&&&&&&&&&&Prints&:&&&&&&&&&&&&string(4)&=&&"test"&&&&&&&&*/&&&&&&&&//----------------------------------------------------//&&&&&&&&var_dump(GetArrKey(&$findArray,&array(&"second_dim",&1&)&)&);&&&&&&&&/*&&&&&&&&&&&&Prints&:&&&&&&&&&&&&string(19)&=&&"second_dim_in_val_1"&&&&&&&&*/&&&&&&&&//----------------------------------------------------//&&&&&&&&var_dump(GetArrKey(&$findArray,&array(&"second_dim",&1,&1&)&)&);&&&&&&&&/*&&&&&&&&&&&&Prints&:&&&&&&&&&&&&std_object&=&&NULL&&&&&&&&*/?&
Better&solution&of&multidimensional&searching.
&?php
function&multidimensional_search($parents,&$searched)&{
&&if&(empty($searched)&||&empty($parents))&{
&&&&return&false;
&&}
&
&&foreach&($parents&as&$key&=&&$value)&{
&&&&$exists&=&true;
&&&&foreach&($searched&as&$skey&=&&$svalue)&{
&&&&&&$exists&=&($exists&&&&IsSet($parents[$key][$skey])&&&&$parents[$key][$skey]&==&$svalue);
&&&&}
&&&&if($exists){&return&$key;&}
&&}
&
&&return&false;
}
$parents&=&array();
$parents[]&=&array('date'=&,&'uid'=&3);
$parents[]&=&array('date'=&,&'uid'=&5);
$parents[]&=&array('date'=&,&'uid'=&5);
echo&multidimensional_search($parents,&array('date'=&,&'uid'=&5));&//&1
?&
Example&of&a&recursive&binary&search&that&returns&the&index&rather&than&boolean.&?php//&returns&the&index&of&needle&in&haystackfunction&binSearch($needle,&$haystack){&&&&//&n&is&only&needed&if&counting&depth&of&search&&&&global&$n;&&&&$n++;&&&&//&get&the&length&of&passed&array&&&&$l&=&count($haystack);&&&&//&if&length&is&0,&problem&&&&if($l&&=&0)&&&&{&&&&&&&&return&-1;&&&&}&&&&//&get&the&mid&element&&&&$m&=&(($l+($l%2))/2);&&&&//&if&mid&&=&length&(e.g.&l=1)&&&&if($m&&=&$l)&&&&{&&&&&&&&$m&=&$m-1;&&&&}&&&&//&get&the&indexed&element&to&compare&to&the&passed&element&and&branch&accordingly&&&&$compare&=&$haystack[$m];&&&&switch(true)&&&&{&&&&&&&&case($compare&$needle):&&&&&&&&{&&&&&&&&&&&&//&recurse&on&the&lower&half&&&&&&&&&&&&$new_haystack&=&array_slice($haystack,&0,&$m);&&&&&&&&&&&&$c&=&count($new_haystack);&&&&&&&&&&&&$r&=&binSearch($needle,&$new_haystack);&&&&&&&&&&&&//&return&current&index&-&(length&of&lower&half&-&found&index&in&lower&half)&&&&&&&&&&&&return&$m&-&($c&-&$r);&&&&&&&&&&&&&&&&&&&&}&&&&&&&&case($compare&$needle):&&&&&&&&{&&&&&&&&&&&&//&recurse&on&the&upper&half&&&&&&&&&&&&$new_haystack&=&array_slice($haystack,&$m,&($l-$m));&&&&&&&&&&&&$c&=&count($new_haystack);&&&&&&&&&&&&$r&=&binSearch($needle,&$new_haystack);&&&&&&&&&&&&//&return&current&position&+&found&index&in&upper&half&&&&&&&&&&&&return&$m&+&$r;&&&&&&&&&&&&&&&&&&&&}&&&&&&&&case($compare==$needle):&&&&&&&&{&&&&&&&&&&&&//&found&it,&so&return&index&&&&&&&&&&&&return&$m;&&&&&&&&&&&&&&&&&&&&}&&&&}}?&
Here&is&a&version&of&binary&search&that&is&done&via&recursion&instead&of&iteration.&&Remember&that&your&data&needs&to&be&presorted!
&?php
static&function&Bin_Search(&$needle,&&$haystack,&$start,&$end)&{
&&&&&&&&if($end&&&$start)
&&&&&&&&{
&&&&&&&&&&&&return&false;
&&&&&&&&}
&&&&&&&&$mid&=&(int)(($end&-&$start)&/&2)&+&$start;
&&
&&&&&&&&if($haystack[$mid]&&&$needle)
&&&&&&&&{
&&&&&&&&&&&&return&Bin_Search($needle,&$haystack,&$start,&$mid&-&1);
&&&&&&&&}
&&&&&&&&else&if($haystack[$mid]&&&$needle)
&&&&&&&&{
&&&&&&&&&&&&return&Bin_Search($needle,&$haystack,&$mid&+&1,&$end);
&&&&&&&&}
&&&&&&&&else
&&&&&&&&{
&&&&&&&&&&&&return&true;
&&&&&&&&}
}
?&
Array&AFTER/BEFORE&Function
function&made&to&mimic&the&jQuery&function&to&insert&items/arrays&into&another&array&before&or&after&a&specific&key.&It&is&split&into&two&functions&for&reuse&to&find&the&offset&of&a&key.&it&detects&if&the&array&is&associative&(can&also&be&manually&controlled)&and&adds&the&keys&where&needed.&if&the&inserted&array&is&associative&then&any&overlapping&keys&will&be&replaced&by&the&new&ones.
array_insert(array&&$original&,&mixed&$insert=null&,&var&$position='after'&,&$key=null&[,&$keep_keys=true])
options&for&$position&=&(after|before)
&?php
function&key_offset(&$array,&$searchKey){
&&&&if(is_array($array)&&&&array_key_exists($searchKey,&$array)){
&&&&&&&&$counter&=&0;
&&&&&&&&foreach($array&as&$key&=&&$value){
&&&&&&&&&&&&if($searchKey&==&$key){
&&&&&&&&&&&&&&&&return&$counter;
&&&&&&&&&&&&}&else&{
&&&&&&&&&&&&&&&&$counter++;
&&&&&&&&&&&&}
&&&&&&&&}
&&&&}
}
function&array_insert(&$original,&$insert=null,&$position='after',&$key=null,&$sens=true){
&&&&if(!empty($insert)){&&&&
&&&&&&&&&&&$after&=&$position&==&'after'&?&true&:&false;
&&&&&&&&&&&$insert&=&(array)$insert;&&&&&&&&&&&
&&&&&&&&&&&$assoc&=&(array_keys($insert)&!==&range(0,&count($insert)-1));&&&&&&&&&&&
&&&&&&&&&&&$keep_keys&=&is_string($insert)&||&!$assoc&||&$sens;
&&&&&&&&&&&
&&&&&&&&if(!empty($key)&&&&array_key_exists($key,&$original)){&&&&
&&&&&&&&&&&&$start&=&key_offset($original,&$key);
&&&&&&&&&&&&&&&$start&=&$after&?&$start+1&:&$start;
&&&&&&&&&&&&if(!$keep_keys){&&&&
&&&&&&&&&&&&&&&&array_Splice($original,$start,0,$insert);
&&&&&&&&&&&&&&&&}&else&{
&&&&&&&&&&&&&&&&$keys&=&array_Keys($original);
&&&&&&&&&&&&&&&&$values&=&array_Values($original);
&&&&&&&&&&&&&&&&$insert&=&(array)$insert;
&&&&&&&&&&&&&&&&$rKeys&=&array_Keys($insert);
&&&&&&&&&&&&&&&&$rValues&=&array_Values($insert);
&&&&&&&&&&&&&&&&array_Splice($keys,$start,0,$rKeys);
&&&&&&&&&&&&&&&&array_Splice($values,$start,0,$rValues);
&&&&&&&&&&&&&&&&&&&&$original&=&array_Combine($keys,$values);
&&&&&&&&&&&&&&&&}
&&&&&&&&}&else&{
&&&&&&&&&&&&$original&=&$after&?&array_merge($original,&$insert)&:&array_merge($insert,&$original);
&&&&&&&&}
&&&&}
}
$insert&=&array('omg'=&&'it&works',&'this_is'&=&&'awsome',&'r'&=&103,104);
$insert2&=&range(11,15);
$insert3&=&array(100=&101,102,103,104);
$original=range(1,10);
array_insert($original,&$insert,&'after',&4);
$original=range(1,10);
array_insert($original,&$insert,&'after',&4,&false);
$original=range(1,10);
array_insert($original,&$insert2,&'after',&4);
$original=range(1,10);
array_insert($original,&$insert3,&'after',&4);
/*
Array
(
&&&&[0]&=&&104
&&&&[1]&=&&2
&&&&[2]&=&&3
&&&&[3]&=&&4
&&&&[4]&=&&5
&&&&[omg]&=&&it&works
&&&&[this_is]&=&&awsome
&&&&[r]&=&&103
&&&&[5]&=&&6
&&&&[6]&=&&7
&&&&[7]&=&&8
&&&&[8]&=&&9
&&&&[9]&=&&10
)
Array
(
&&&&[0]&=&&1
&&&&[1]&=&&2
&&&&[2]&=&&3
&&&&[3]&=&&4
&&&&[4]&=&&5
&&&&[5]&=&&it&works
&&&&[6]&=&&awsome
&&&&[7]&=&&103
&&&&[8]&=&&104
&&&&[9]&=&&6
&&&&[10]&=&&7
&&&&[11]&=&&8
&&&&[12]&=&&9
&&&&[13]&=&&10
)
Array
(
&&&&[0]&=&&11
&&&&[1]&=&&12
&&&&[2]&=&&13
&&&&[3]&=&&14
&&&&[4]&=&&15
&&&&[5]&=&&6
&&&&[6]&=&&7
&&&&[7]&=&&8
&&&&[8]&=&&9
&&&&[9]&=&&10
)
Array
(
&&&&[0]&=&&1
&&&&[1]&=&&2
&&&&[2]&=&&3
&&&&[3]&=&&4
&&&&[4]&=&&5
&&&&[100]&=&&101
&&&&[101]&=&&102
&&&&[102]&=&&103
&&&&[103]&=&&104
&&&&[5]&=&&6
&&&&[6]&=&&7
&&&&[7]&=&&8
&&&&[8]&=&&9
&&&&[9]&=&&10
)
*/
?&
I&found&a&simple&script&to&remove&certain&values&from&a&array.I&use&it&when&using&the&scandir&function,&because&i&don't&want&certain&items&in&the&array&(like&the&.,&..&folders&and&the&thumbs.db)&?php$music&=&scandir("music");unset($music[array_search('.',$music)]);&&//&Removing&the&.&directoryunset($music[array_search('..',$music)]);&//&Removing&the&..&directoryunset($music[array_search('Thumbs.db',$music)]);&//&Removing&the&Thumbs.db&fileunset($music[array_search('thumbs.db',$music)]);&//&Removing&the&thumbs.db&file?&
Recently&I&had&to&get&all&locations&of&a&one-dimensional&non-associative&array&(needle,&not&array&of&needles)&in&another&one-dimensional&non-associative&array&(haystack)&without&using&more&memory&than&necessary.&I&haven't&found&any&satisfactory&way&to&do&that,&so&I&wrote&the&following&function,&inspired&by&the&array_slice()&source&code.
Notes:
0.&$offset,&$length&and&$strict&behave&the&same&way&as&those&for&array_slice()&and&array_search();
1.&this&function&doesn't&use&foreach&or&array_slice(),&neither&does&it&modify&$needle&or&$haystack,&so&no&temporary&copies&are&needed/created,&regardless&of&whether&the&arguments&are&passed&by&reference&or&not&--&useful&when&dealing&with&very&large&haystacks&and&
2.&$needle&and&$haystack&are&typecast&to&array&if&they're&not&
3.&you&can&specify&the&$start&position&to&start&searching&from&in&the&$haystack&(default&is&0);
4.&negative&$start&values&can&be&used&if&you&want&to&specify&the&starting&position&from&the&end&of&$haystack.
5.&you&can&specify&the&search&$length,&starting&from&$&a&negative&value&stops&the&search&at&that&many&elements&from&the&end&of&the&
6.&pass&true&as&the&fifth&argument&to&do&a&strict&search&(not&tested&on&objects);
7.&the&function&returns&an&array&if&it&finds&one&or&more&occurrences&of&$needle&in&the&$haystack,&false&on&failure.
8.&keys&are&
9.&if&you&want&to&get&only&the&first&location&of&$needle&in&$haystack,&returned&as&an&integer&rather&than&array&--&in&other&words,&to&make&an&array_match()&function&instead&of&array_match_all()&--&remove&this&line:
&&$results&=&array();
and&replace:
&&&&if&($found)
&&&&{
&&&&&&$results[]&=&$i;
&&&&&&$i&+=&$ncount&-&1;
&&&&}
&&}
&&if&(!empty($results))
&&&&return&$
&&else
&&&&return&
&&&&if&($found)
&&&&&&return&$i;
&&}
&&return&
And&now&the&function:
&?php
function&array_match_all($needle,&$haystack,&$offset&=&0,&$length&=&0,&$strict&=&false)
{
&&if&(!is_array($needle))
&&&&$needle&=&(array)&$needle;
&&if&(!is_array($haystack))
&&&&$haystack&=&(array)&$haystack;
&&$offset&=&(int)&$offset;
&&$length&=&(int)&$length;
&&$strict&=&($strict&!=&false);
&&$ncount&=&count($needle);
&&$hcount&=&count($haystack);
&&//&Empty&arrays?&Really?&Also,&no&point&in&dealing&with&a&needle&larger&than&the&haystack.
&&if&(($hcount&==&0)&||&($ncount&==&0)&||&($ncount&&&$hcount))
&&&&return&false;
&&//&Is&offset&beyond&the&upper&bound?
&&if&($offset&&&$hcount&-&$ncount)
&&&&return&false;
&&//&If&offset&is&specified&from&the&end&of&haystack,&is&it&beyond&the&lower&bound?
&&elseif&($offset&&&0&&&&($offset&=&$hcount&+&$offset)&&&0)
&&&&$offset&=&0;
&&//&Determine&the&length.
&&if&($length&==&0)
&&&&$length&=&$hcount;
&&if&($length&&&0)
&&&&$length&=&$hcount&-&$offset&+&$length;
&&elseif&($offset&+&$length&&&$hcount)
&&&&$length&=&$hcount&-&$offset;
&&//&Is&the&needle&larger&than&the&portion&of&the&haystack&we&are&searching&in?
&&if&(($length&&=&1)&||&($ncount&&&$length))
&&&&return&false;
&&//&Determine&the&actual&search&length.
&&$length&=&$offset&+&$length&-&$ncount&+&1;
&&$results&=&array();
&&for&($i&=&$offset;&$i&&&$length;&++$i)
&&{
&&&&$found&=&true;
&&&&for&($j&=&0;&$j&&&$ncount;&++$j)
&&&&{
&&&&&&if&(($strict&&&&($haystack[$i&+&$j]&!==&$needle[$j]))&||&(!$strict&&&&($haystack[$i&+&$j]&!=&$needle[$j])))
&&&&&&{
&&&&&&&&$found&=&false;&&&&&&&&
&&&&&&&&
&&&&&&}
&&&&}
&&&&if&($found)
&&&&{
&&&&&&$results[]&=&$i;
&&&&&&$i&+=&$ncount&-&1;
&&&&}
&&}
&&if&(empty($results))
&&&&return&false;
&&else
&&&&return&$results;
}
?&
for&searching&case&insensitive&better&this:
&?php
array_search(strtolower($element),array_map('strtolower',$array));
?&
for&case&insensitive&array_search&you&could&use:
&?php
function&array_search_i($str,$array){
&&&&foreach($array&as&$key&=&&$value)&{
&&&&&&&&if(stristr($str,$value))&return&$key;
&&&&}
&&&&return&false;
}
?&
Hey&all&-&I&needed&a&function&to&search&for&an&array&in&a&multi-dimensional&array,&but&only&the&keys&I&wanted,&not&all&keys.&Hee&if&my&function:&?phpfunction&my_array_search($needle,&$haystack)&{&&&&&&&&if&(empty($needle)&||&empty($haystack))&{&&&&&&&&&&&&return&false;&&&&&&&&}&&&&&&&&&&&&&&&&foreach&($haystack&as&$key&=&&$value)&{&&&&&&&&&&&&$exists&=&0;&&&&&&&&&&&&foreach&($needle&as&$nkey&=&&$nvalue)&{&&&&&&&&&&&&&&&&if&(!empty($value[$nkey])&&&&$value[$nkey]&==&$nvalue)&{&&&&&&&&&&&&&&&&&&&&$exists&=&1;&&&&&&&&&&&&&&&&}&else&{&&&&&&&&&&&&&&&&&&&&$exists&=&0;&&&&&&&&&&&&&&&&}&&&&&&&&&&&&}&&&&&&&&&&&&if&($exists)&return&$key;&&&&&&&&}&&&&&&&&&&&&&&&&return&false;&&&&}?&Examples:&?php$needle&=&array('date_start'&=&&'27-10-2010',&'date_end'&=&&'29-10-2010');$haystack&=&array();$haystack[]&=&array('date_start'&=&&'25-10-2010',&'date_end'&=&&'26-10-2010',&'promos'&=&&array('test',&'test1');$haystack[]&=&array('date_start'&=&&'27-10-2010',&'date_end'&=&&'28-10-2010',&'promos'&=&&array('test2',&'test3');$haystack[]&=&array('date_start'&=&&'27-10-2010',&'date_end'&=&&'29-10-2010',&'promos'&=&&array('test4',&'test5');$key&=&my_array_search($needle,&$haystack);//&will&output&(bool)false&for&not&found&or&(int)key_no&with&the&key&number//&this&example&outputs&(int)2var_dump($key);?&I&hope&this&function&will&help&someone!
I&needed&to&check&an&array&for&a&value&but&the&value&only&had&to&match&part&of&a&string&in&the&array&value&so&i&wrote&this&little&function&hope&it&helps&someone&out&(also&some&documentation&of&what&used&to&test&if&there&already&was&such&a&function&'couse&i&was&hoping&array_search&was&this.&?phpfunction&my_array_search($needle&=&null,&$haystack_array&=&null,&$skip&=&0){&&&&if($needle&==&null&||&$haystack_array&==&null)&&&&&&&&die('$needle&and&$haystack_array&are&mandatory&for&functie&my_array_search()');&&&&foreach($haystack_array&as&$key&=&&$eval)&&&&{&&&&&&&&if($skip&!=&0)$eval&=&substr($eval,&$skip);&&&&&&&&if(stristr($eval,&$needle)&!==&false)&return&true;&&&&}&&&&return&false;}$arr&=&array('foo',&'bar');echo&'using&in_array&br&/&';if(in_array('ar',&$arr)&===&true)echo&'ar&found&br&/&';if(in_array('bar',&$arr)&===&true)echo&'bar&found&br&/&';echo&'using&array_search&br&/&';if(array_search('ar',&$arr)&!==&false)echo&'ar&found&br&/&';if(array_search('bar',&$arr)&!==&false)echo&'bar&found&br&/&';echo&'using&my_array_search&br&/&';if(my_array_search('ar',&$arr)&!==&false)echo&'ar&found&br&/&';if(my_array_search('bar',&$arr)&!==&false)echo&'bar&found&br&/&';?&returns:using&in_arraybar&foundusing&array_searchbar&foundusing&my_array_searchar&foundbar&found
The getParentStack is also working if you work with JSON records that are encoded. Following sample:
$in = '{&total&:&2&,&records&: [{&id&:&25&},{&id&:&32&}]}'; // string!!!
$json = json_decode( $in, true ); //don't forget the true here
$s = getParentStack(32, $json['records']) ;
then test this with:
if ($s != false)
// then it is found, don't test true here!!!
or test direct with:
if ( getParentStack(32, $json['records']) != false )
It works great with my JSON's thanks Robert Gonzalez
I&needed&a&way&to&find&the&parent&hierarchy&of&a&multidimensional&array.&Being&the&rogue&that&I&am,&I&got&to&coding&before&searching&the&manual&and&came&up&with&two&little&functions&that&will&return&a&parent&stack&for&a&first&find&and&a&complete&parent&stack,&similar&in&nature&to&the&solution&presented&by&jette&at&nerdgirl&dot&dk&without&all&the&extra&stuff&or&use&of&eval().&;)&?php/**&*&Gets&the&parent&stack&of&a&string&array&element&if&it&is&found&within&the&&*&parent&array&*&&*&This&will&not&search&objects&within&an&array,&though&I&suspect&you&could&&*&tweak&it&easily&enough&to&do&that&*&*&@param&string&$child&The&string&array&element&to&search&for&*&@param&array&$stack&The&stack&to&search&within&for&the&child&*&@return&array&An&array&containing&the&parent&stack&for&the&child&if&found,&*&&&&&&&&&&&&&&&false&otherwise&*/function&getParentStack($child,&$stack)&{&&&&foreach&($stack&as&$k&=&&$v)&{&&&&&&&&if&(is_array($v))&{&&&&&&&&&&&&//&If&the&current&element&of&the&array&is&an&array,&recurse&it&and&capture&the&return&&&&&&&&&&&&$return&=&getParentStack($child,&$v);&&&&&&&&&&&&&&&&&&&&&&&&//&If&the&return&is&an&array,&stack&it&and&return&it&&&&&&&&&&&&if&(is_array($return))&{&&&&&&&&&&&&&&&&return&array($k&=&&$return);&&&&&&&&&&&&}&&&&&&&&}&else&{&&&&&&&&&&&&//&Since&we&are&not&on&an&array,&compare&directly&&&&&&&&&&&&if&($v&==&$child)&{&&&&&&&&&&&&&&&&//&And&if&we&match,&stack&it&and&return&it&&&&&&&&&&&&&&&&return&array($k&=&&$child);&&&&&&&&&&&&}&&&&&&&&}&&&&}&&&&&&&&//&Return&false&since&there&was&nothing&found&&&&return&false;}/**&*&Gets&the&complete&parent&stack&of&a&string&array&element&if&it&is&found&&*&within&the&parent&array&*&&*&This&will&not&search&objects&within&an&array,&though&I&suspect&you&could&&*&tweak&it&easily&enough&to&do&that&*&*&@param&string&$child&The&string&array&element&to&search&for&*&@param&array&$stack&The&stack&to&search&within&for&the&child&*&@return&array&An&array&containing&the&parent&stack&for&the&child&if&found,&*&&&&&&&&&&&&&&&false&otherwise&*/function&getParentStackComplete($child,&$stack)&{&&&&$return&=&array();&&&&foreach&($stack&as&$k&=&&$v)&{&&&&&&&&if&(is_array($v))&{&&&&&&&&&&&&//&If&the&current&element&of&the&array&is&an&array,&recurse&it&&&&&&&&&&&&&//&and&capture&the&return&stack&&&&&&&&&&&&$stack&=&getParentStackComplete($child,&$v);&&&&&&&&&&&&&&&&&&&&&&&&//&If&the&return&stack&is&an&array,&add&it&to&the&return&&&&&&&&&&&&if&(is_array($stack)&&&&!empty($stack))&{&&&&&&&&&&&&&&&&$return[$k]&=&$stack;&&&&&&&&&&&&}&&&&&&&&}&else&{&&&&&&&&&&&&//&Since&we&are&not&on&an&array,&compare&directly&&&&&&&&&&&&if&($v&==&$child)&{&&&&&&&&&&&&&&&&//&And&if&we&match,&stack&it&and&return&it&&&&&&&&&&&&&&&&$return[$k]&=&$child;&&&&&&&&&&&&}&&&&&&&&}&&&&}&&&&&&&&//&Return&the&stack&&&&return&empty($return)&?&false:&$return;}//&TESTING$array&=&array(&&&&'balloon'&=&&array(&&&&&&&&'red'&=&&array(1&=&&'Love',&'Valentine',&'Heart',),&&&&&&&&'green'&=&&array(1&=&&'Summertime',&'Hope',),&&&&),&&&&'ribbon'&=&&array(&&&&&&&&'yellow'&=&&array(2&=&&'Welcome',),&&&&&&&&'red'&=&&array(3&=&&'Love',&'Love',),&&&&),);$s&=&getParentStack('Love',&$array);$c&=&getParentStackComplete('Love',&$array);var_dump($s,&$c);?&Output:array&&'balloon'&=&&&&&&array&&&&&&'red'&=&&&&&&&&&&array&&&&&&&&&&1&=&&string&'Love'&(length=4)array&&'balloon'&=&&&&&&array&&&&&&'red'&=&&&&&&&&&&array&&&&&&&&&&1&=&&string&'Love'&(length=4)&&'ribbon'&=&&&&&&array&&&&&&'red'&=&&&&&&&&&&array&&&&&&&&&&3&=&&string&'Love'&(length=4)&&&&&&&&&&4&=&&string&'Love'&(length=4)
In&this&code&I&write&a&code&to&find&next&and&previous&element&of&an&array&using&current&element&of&that&array.&Let&suppose&if&we&are&in&element&9&and&have&to&access&its&next&and&previous&element&then&this&code&be&helpful&for&someone.&?php$myArray&=&array(4,5,7,9,10,11,13,19,25);$currentElement&=&9;$firstElement&=&current($myArray);$lastElement&=&$myArray[sizeof($myArray)-1];$currentKey&=&array_search($currentElement,&$myArray);$currentValue&=&$myArray[$currentKey];$previousValue&=&"";$nextValue&=&"";if($currentElement!=$lastElement){&&&&$nextKey&=&$currentKey&+&1;&&&&$nextValue&=&$myArray[$nextKey];}if($currentElement!=$firstElement){&&&&$previousKey&=&$currentKey&-&1;&&&&$previousValue&=&$myArray[$previousKey];}echo&$previousValue."--".$currentValue."--".$nextValue;?&Thanks,Hanan&Ali
This&a&simple&and&lazy&lazy&method&to&search&a&key&name&in&an&array&by&pattern,&and&return&the&value&if&it&isn't&empty.
&?php
function&array_search_key($p,&$a)
{
&&&&foreach&($a&as&$k&=&&$v)&{
&&&&&&&&if(strstr($k,&$p)){
&&&&&&&&&&&&if(!empty($v)&||&$v&&&0){
&&&&&&&&&&&&&&&&return&$v;
&&&&&&&&&&&&}
&&&&&&&&}
&&&&}
}
?&
If&you&want&a&very&simple&way&of&searching&a&value&through&a&multidimensionnal&array&here's&a&&trick&:&
&?php
function&recursiveArraySearch($haystack,&$needle,&$index&=&null)
{
&&&&$aIt&&&&&=&new&RecursiveArrayIterator($haystack);
&&&&$it&&&&=&new&RecursiveIteratorIterator($aIt);
&&&&
&&&&while($it-&valid())
&&&&{&&&&&&&&
&&&&&&&&if&(((isset($index)&AND&($it-&key()&==&$index))&OR&(!isset($index)))&AND&($it-&current()&==&$needle))&{
&&&&&&&&&&&&return&$aIt-&key();
&&&&&&&&}
&&&&&&&&
&&&&&&&&$it-&next();
&&&&}
&&&&
&&&&return&false;
}
?&
So&let's&take&a&misc&multi-dimensionnal&array&:&
&?php
$std&=&new&stdClass();
$std-&name&&&&&=&'luke';
$std-&age&&&&&=&'25';
$std-&sex&&&&&=&'M';
$array&&&&&=&array(&&&&array('type'=&'dog',&'name'=&'butch',&'sex'=&'m',&'breed'=&'boxer'),
&&&&&&&&&&&&&&&&&&&&array('type'=&'dog',&'name'=&'fido',&'sex'=&'m',&'breed'=&'doberman'),
&&&&&&&&&&&&&&&&&&&&'simpleValue',
&&&&&&&&&&&&&&&&&&&&array('type'=&'cat',&'name'=&'tiddles','sex'=&'m',&'breed'=&'maine&coon'),
&&&&&&&&&&&&&&&&&&&&array('type'=&'horse',&'name'=&'ed','sex'=&'m',&'breed'=&'clydesdale'),
&&&&&&&&&&&&&&&&&&&&$std);
echo&recursiveArraySearch($array,&'25',&'age');&&&&&&&&//&returns&5
echo&recursiveArraySearch($array,&'25',&'name');&&&&//&returns&false
echo&recursiveArraySearch($array,&'simpleValue');&&&&//&returns&2
echo&recursiveArraySearch($array,&'fido');&&&&&&&&&&&&//&returns&1
?&
I&was&looking&around&for&a&recursive&search&by&keys&in&multidimensional&arrays.&After&testing&the&ones&in&this&thread&seems&noone&accually&works.&So&I&put&this&one&together,&and&it&does&what&you&expect&it&to&do.
You&need&to&find&the&value&for&the&key&"han-solo".
&?php
if(&($val&=&array_search_key('han-solo',$array))&!==&false){
&&var_dump($val);
}&else&{
&&//&No&keys&with&the&name&"han-solo"
}
function&array_search_key(&$needle_key,&$array&)&{
&&foreach($array&AS&$key=&$value){
&&&&if($key&==&$needle_key)&return&$value;
&&&&if(is_array($value)){
&&&&&&if(&($result&=&array_search_key($needle_key,$value))&!==&false)
&&&&&&&&return&$result;
&&&&}
&&}
&&return&false;
}
?&
I&needed&a&case&insensitive&array&search&function&for&a&project...
&?php
/**
&*&Performs&the&same&function&as&array_search&except&that&it&is&case
&*&insensitive
&*&@param&mixed&$needle
&*&@param&array&$haystack
&*&@return&mixed
&*/
function&array_nsearch($needle,&array&$haystack)&{
&&&$it&=&new&IteratorIterator(new&ArrayIterator($haystack));
&&&foreach($it&as&$key&=&&$val)&{
&&&&&&&if(strcasecmp($val,$needle)&===&0)&{
&&&&&&&&&&&return&$key;
&&&&&&&}
&&&}
&&&return&false;
}
?&
I&use&this&function&to&search&the&value&of&arrays&of&any&dimension,&and&return&the&result&with&keys&preserved:&?phpfunction&multiArrayValueSearch($haystack,&$needle,&&$result,&&$aryPath=NULL,&$currentKey='')&{&&if&(is_array($haystack))&{&&&&$count&=&count($haystack);&&&&$iterator&=&0;&&&&foreach($haystack&as&$location&=&&$straw)&{&&&&&&$iterator++;&&&&&&$next&=&($iterator&==&$count)?false:true;&&&&&&if&(is_array($straw))&$aryPath[$location]&=&$location;&&&&&&&&multiArrayValueSearch($straw,$needle,$result,$aryPath,$location);&&&&&&&&if&(!$next)&{&&&&&&&&&&unset($aryPath[$currentKey]);&&&&&&&&}&&&&&&}&&&&}&else&{&&&&&&$straw&=&$haystack;&&&&&&if&($straw&==&$needle)&{&&&&&&&&if&(!isset($aryPath))&{&&&&&&&&&&$strPath&=&"\$result[$currentKey]&=&\$";&&&&&&&&}&else&{&&&&&&&&&&$strPath&=&"\$result['".join("']['",$aryPath)."'][$currentKey]&=&\$";&&&&&&&&}&&&&&&&&eval($strPath);&&&&&&}&&&}}?&Example:&?php$ary['ballon']['red'][1]&=&'Love';$ary['ballon']['red'][2]&=&'Valentine';$ary['ballon']['red'][3]&=&'Heart';$ary['ballon']['green'][1]&=&'Summertime';$ary['ballon']['green'][2]&=&'Hope';$ary['ribbon']['yellow'][2]&=&'Welcome';$ary['ribbon']['red'][3]&=&'Love';$ary['ribbon']['red'][4]&=&'Love';echo&"&pre&";//Just&call&the&function&with&3&first&parameters&set://&&1)&The&array&to&search//&&2)&The&value&to&find//&&3)&A&variable&to&store&the&resultmultiArrayValueSearch($ary,'Love',$match);print_r($match);echo&"&/pre&";?&Output:Array(&&&&[ballon]&=&&Array&&&&&&&&(&&&&&&&&&&&&[red]&=&&Array&&&&&&&&&&&&&&&&(&&&&&&&&&&&&&&&&&&&&[1]&=&&Love&&&&&&&&&&&&&&&&)&&&&&&&&)&&&&[ribbon]&=&&Array&&&&&&&&(&&&&&&&&&&&&[red]&=&&Array&&&&&&&&&&&&&&&&(&&&&&&&&&&&&&&&&&&&&[3]&=&&Love&&&&&&&&&&&&&&&&&&&&[4]&=&&Love&&&&&&&&&&&&&&&&)&&&&&&&&))You&can&easily&adapt&it&to&suit&your&need&of&matching,&by&changing&line&16&in&the&function:&?phpif&($straw&==&$needle)&{?&
A&couple&of&staple&custom&PHP&array&searching&functions&I&rely&on&in&most&of&my&&?php&&&&//&array_search&with&partial&matches&and&optional&search&by&key&&&&function&array_find($needle,&$haystack,&$search_keys&=&false)&{&&&&&&&&if(!is_array($haystack))&return&false;&&&&&&&&foreach($haystack&as&$key=&$value)&{&&&&&&&&&&&&$what&=&($search_keys)&?&$key&:&$value;&&&&&&&&&&&&if(strpos($what,&$needle)!==false)&return&$key;&&&&&&&&}&&&&&&&&return&false;&&&&}&&&&&&&&//&array_search&with&recursive&searching,&optional&partial&matches&and&optional&search&by&key&&&&function&array_find_r($needle,&$haystack,&$partial_matches&=&false,&$search_keys&=&false)&{&&&&&&&&if(!is_array($haystack))&return&false;&&&&&&&&foreach($haystack&as&$key=&$value)&{&&&&&&&&&&&&$what&=&($search_keys)&?&$key&:&$value;&&&&&&&&&&&&if($needle===$what)&return&$key;&&&&&&&&&&&&else&if($partial_matches&&&&@strpos($what,&$needle)!==false)&return&$key;&&&&&&&&&&&&else&if(is_array($value)&&&&array_find_r($needle,&$value,&$partial_matches,&$search_keys)!==false)&return&$key;&&&&&&&&}&&&&&&&&return&false;&&&&}?&Hope&they&help&someone!
If&you&search&a&key&position&in&an&associative&array&(keys&are&uniques),&i&suggest&this&function&:&?phppublic&function&getKeyPositionInArray($haystack,&$keyNeedle){&&&&$i&=&0;&&&&foreach($haystack&as&$key&=&&$value)&&&&{&&&&&&&&if($key&==&$keyNeedle)&&&&&&&&{&&&&&&&&&&&&return&$i;&&&&&&&&}&&&&&&&&$i++;&&&&}}?&
one&thing&to&be&very&aware&of&is&that&array_search()&will&fail&if&the&needle&is&a&string&and&the&array&itself&contains&values&that&are&mixture&of&numbers&and&strings.&&(or&even&a&string&that&looks&like&a&number)
The&problem&is&that&unless&you&specify&"strict"&the&match&is&done&using&==&&&&and&in&that&case&any&string&will&match&a&numeric&value&of&zero&which&is&not&what&you&want.
also,&php&can&lookup&an&index&pretty&darn&fast.&&for&many&scenarios,&it&is&practical&to&maintain&multiple&arrays,&one&in&which&the&index&of&the&array&is&the&search&key&and&the&normal&array&that&contains&the&data.
&&$normal[$index]&=&array('key'=&$key,&'data'=&'foo');
&&$inverse[$key]&=&$index;
&&//very&fast&lookup,&this&beats&any&other&kind&of&search
&&if&(array_key_exists($key,&$inverse))&
&&{
&&&&$index&=&$inverse[$key];
&&&&return&$normal[$index];
&&}
The&return&value&for&array_search&is&confusing&if&the&return&key&is&zero.&it&is&better&to&double&check&it&with&in_array()&function.Example:&?php$SampleArray&=&('a',&'b',&'c');$Key&=&array_search('a',&$SampleArray);$Zero&=&in_array('a',&$SampleArray);if($Key&==&NULL&&&&!$Zero)&&&echo&"Key&doesnt&exists";else&&&echo&"Key&exists";&?&
if $haystack is not an array, for example false from some previous action, the function returns null instead of false in php 5.3.
Sometimes&you&need&to&find&a&given&value&in&a&sorted&array&or&-&if&not&found&-&detect&the&place&where&it&should&be.&After&that&you&can&for&example&split&the&array&into&two&halves,&the&&greater&and&the&smaller&one.greenmr,&dennis.decoene&and&php&at&celerondude&had&all&posted&very&good&binary&search&functions&but&these&functions&all&return&false&if&the&needle&was&not&found&in&the&haystack.&I've&tweaked&greenmr's&code&a&little:&?phpfunction&Array_BinarySearch(&$needle,&$haystack,&$comparator&,&&$probe&){&&&&$high&=&Count(&$haystack&)&-1;&&&&$low&=&0;&&&&&&&&while&(&$high&&=&$low&)&&&&{&&&&&&&&$probe&=&Floor(&(&$high&+&$low&)&/&2&);&&&&&&&&$comparison&=&$comparator(&$haystack[$probe],&$needle&);&&&&&&&&if&(&$comparison&&&0&)&&&&&&&&{&&&&&&&&&&&&$low&=&$probe&+1;&&&&&&&&}&&&&&&&&elseif&(&$comparison&&&0&)&&&&&&&&&{&&&&&&&&&&&&$high&=&$probe&-1;&&&&&&&&}&&&&&&&&else&&&&&&&&{&&&&&&&&&&&&return&true;&&&&&&&&}&&&&}&&&&//The&loop&ended&without&a&match&&&&&//Compensate&for&needle&greater&than&highest&haystack&element&&&&if($comparator($haystack[count($haystack)-1],&$needle)&&&0)&&&&{&&&&&&&&$probe&=&count($haystack);&&&&}&&&&&return&false;}?&Now,&the&function&returns&true&if&it&finds&something&and&false&otherwise.&If&a&needle&was&found,&then&$probe&will&contain&it's&position.&Otherwise,&$probe&will&contain&position&of&where&the&needle&would&be&if&it&were&there&:).&This&is&possible&because&we&pass&$probe&by&reference.Example:&?php//ultra-simple&comparator&:)function&CompareNumbers($obj,&$needle){&&&&return&$obj&-&$needle;}//use&examples$testArr&=&array(10,&20,&30,&40,&50);$res&=&Array_BinarySearch(30,&$testArr,&'CompareNumbers',&$probe);echo&(int)$res.'&'.$probe.'&br&/&';//output&is:&1&2&-&found&at&position&2$res&=&Array_BinarySearch(45,&$testArr,&'CompareNumbers',&$probe);echo&(int)$res.'&'.$probe.'&br&/&';//output&is:&0&4&-&not&found,&but&it&would&be&at&position&4&(between&40&and&45)&$res&=&Array_BinarySearch(-3,&$testArr,&'CompareNumbers',&$probe);echo&(int)$res.'&'.$probe.'&br&/&';//output&is:&0&0&-&not&found,&but&it&would&be&at&position&0&(before&10)$res&=&Array_BinarySearch(300,&$testArr,&'CompareNumbers',&$probe);echo&(int)$res.'&'.$probe.'&br&/&';//output&is:&0&5&-&not&found,&but&it&would&be&at&position&5&(after&50;&note,&that&count($haystack)&==&5)?&See&original&greenmr's&note&for&additional&details&about&usage&of&this&binary&search:&http://php.net/manual/en/function.array-search.php#89413
You&can&remove&some&values&from&array,&by&using&unset()&and&array_search().&?php$friends&=&array(&'Bob',&'Ann',&'Peter'&);&//&Two&persons&named&'Bob'$find&=&'Bob';$key&=&array_search(&$find,&$friends&);&//&Find&key&of&given&valueif&($key&!=&NULL&||&$key&!==&FALSE)&{&&&&unset($friends[$key]);&//&remove&key&from&array}//&Now,&$friends&=&array(&'Ann',&'Peter');?&
The&original&function&for&searching&a&multidimensional&array&didn't&let&you&filter&by&arraykeys.This&one&is&modified&so&you&can&search&by&array&keys&or&not.If&you&want&a&general&search&for&a&value&and&don't&care&which&specific&key&to&target&you&dont&have&to&specify&it&but&example.&?php$array&=&("shoes"&=&&array("test1"=&&"123","test2"=&"1234","test3"=&"12345"),&&&&&&&&&&&&&"shoes2"=&&array("test1"=&"324","test2"=&"3515","test3"=&"123131");array_search_value("123",$array,"test1");&//&would&return&shoesarray_search_value("12223",$array,"test1");&//&would&return&?&this&makes&it&easier&to&validate&a&multi-dimensional&array&to&make&sure&certain&data&is&present.Enjoy!&?phpfunction&array_search_value($needle,$haystack,$arraykey=FALSE)&{&&&&foreach($haystack&as&$key=&$value)&{&&&&&&&&$current_key=$key;&&&&&&&&if($arraykey){&&&&&&&&&&&&&&&&&&&&&&&&if($needle&==&$value[$arraykey]){&&&&&&&&&&&&return&$value['id'];&&&&&&&&&&&&}&&&&&&&&&&&&&&&&&&&&&&&&if(array_search_value($needle,$value[$arraykey])&==&true)&{&&&&&&&&&&&&return&$current_key;&&&&&&&&&&&&}&&&&&&&&&&&&&&&&&&&&}else{&&&&&&&&&&&&&&&&&&&&&&&&if($needle&==&$value)&&&&&&&&&&&&return&$value;&&&&&&&&&&&&&&&&&&&&&&&&if(array_search_value($needle,$value)&==&true)&{&&&&&&&&&&&&&&&&return&$current_key;&&&&&&&&&&&&}&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&&&&&}&&&&return&false;}?&
Made&a&function&that&I&used&to&search&the&$_SERVER&variable&(&http://php.net/reserved.variables.server&)&for&matches&to&getcwd&(&http://php.net/getcwd&)&excluding&some&key's&that&I&don't&want.
&?php
/**
&*&Returns&all&key/values&in&array&that&match.
&*
&*&@param&$needle
&*&&What&your&searching&for
&*&@param&$haystack
&*&&Array&of&values
&*&@param&$a_not
&*&&Optional&array&of&key&names&to&exclude
&*/
function&boost_array_find($needle,&$haystack,&$a_not&=&array())&{
&&$out&=&array();
&&foreach($haystack&as&$key=&$value)&{
&&&&if&(strpos($value,&$needle)&!==&FALSE)&{
&&&&&&$good&=&TRUE;
&&&&&&foreach($a_not&as&$not)&{
&&&&&&&&if&(strpos($key,&$not)&!==&FALSE)&{
&&&&&&&&&&$good&=&FALSE;
&&&&&&&&}
&&&&&&}
&&&&&&if&($good)&{
&&&&&&&&$out[$key]&=&$value;
&&&&&&}
&&&&}
&&}
&&return&$out;
}
//&Example&Usage
$document_root&=&str_replace("\\",&'/',&getcwd());
$rejects&=&array('SCRIPT_FILENAME');
$out&=&boost_array_find($document_root,&$_SERVER,&$rejects);
print_r($out);
?&
Which&should&output&this&on&most&servers.
Array
(
&&&&[DOCUMENT_ROOT]&=&&path/to/webroot
)
On&Mosso's&servers&it&will&output&this
Array
(
&&&&[PHP_DOCUMENT_ROOT]&=&&path/to/webroot
)
Here&is&a&cool&trick:
&?php
function&arr_search&(&$array,&$expression&)&{
&&&&$result&=&array();
&&&&$expression&=&preg_replace&(&"/([^\s]+?)(=|&|&|!)/",&"\$a['$1']$2",&$expression&);
&&&&foreach&(&$array&as&$a&)&if&(&eval&(&"return&$expression;"&)&)&$result[]&=&$a;
&&&&return&$result;
}
$data&=&array&(
&&&&array&(&"name"&=&&"bill",&"age"&=&&40&),
&&&&array&(&"name"&=&&"john",&"age"&=&&30&),
&&&&array&(&"name"&=&&"jack",&"age"&=&&50&),
&&&&array&(&"name"&=&&"john",&"age"&=&&25&)
);
print_r&(&arr_search&(&$data,&"age&=30"&)&);
print_r&(&arr_search&(&$data,&"name=='john'"&)&);
print_r&(&arr_search&(&$data,&"age&25&and&name=='john'"&)&);
?&
--&results&--
Array
(
&&&&[0]&=&&Array
&&&&&&&&(
&&&&&&&&&&&&[name]&=&&bill
&&&&&&&&&&&&[age]&=&&40
&&&&&&&&)
&&&&[1]&=&&Array
&&&&&&&&(
&&&&&&&&&&&&[name]&=&&john
&&&&&&&&&&&&[age]&=&&30
&&&&&&&&)
&&&&[2]&=&&Array
&&&&&&&&(
&&&&&&&&&&&&[name]&=&&jack
&&&&&&&&&&&&[age]&=&&50
&&&&&&&&)
)
Array
(
&&&&[0]&=&&Array
&&&&&&&&(
&&&&&&&&&&&&[name]&=&&john
&&&&&&&&&&&&[age]&=&&30
&&&&&&&&)
&&&&[1]&=&&Array
&&&&&&&&(
&&&&&&&&&&&&[name]&=&&john
&&&&&&&&&&&&[age]&=&&25
&&&&&&&&)
)
Array
(
&&&&[0]&=&&Array
&&&&&&&&(
&&&&&&&&&&&&[name]&=&&john
&&&&&&&&&&&&[age]&=&&30
&&&&&&&&)
the&recursive&function&by&tony&have&a&small&bug.&it&failes&when&a&key&is&0here&is&the&corrected&version&of&this&helpful&function:&?phpfunction&recursive_array_search($needle,$haystack)&{&&&&foreach($haystack&as&$key=&$value)&{&&&&&&&&$current_key=$key;&&&&&&&&if($needle===$value&OR&(is_array($value)&&&&recursive_array_search($needle,$value)&!==&false))&{&&&&&&&&&&&&return&$current_key;&&&&&&&&}&&&&}&&&&return&false;}?&
A&simple&recursive&array_search&function&:&
&?php
function&recursive_array_search($needle,$haystack)&{
&&&&foreach($haystack&as&$key=&$value)&{
&&&&&&&&$current_key=$key;
&&&&&&&&if($needle===$value&OR&(is_array($value)&&&&recursive_array_search($needle,$value)))&{
&&&&&&&&&&&&return&$current_key;
&&&&&&&&}
&&&&}
&&&&return&false;
}
?&
If&you&only&know&a&part&of&a&value&in&an&array&and&want&to&know&the&complete&value,&you&can&use&the&following&function:&?phpfunction&array_find($needle,&$haystack){&&&foreach&($haystack&as&$item)&&&{&&&&&&if&(strpos($item,&$needle)&!==&FALSE)&&&&&&{&&&&&&&&&return&$item;&&&&&&&&&&&&&&&}&&&}}?&The&function&returns&the&complete&first&value&of&$haystack&that&contains&$needle.
Can&be&useful&for&searching&in&a&multi-dimensional&array:
&?php
function&array_search_in_level($needle,&$haystack,&$key,&&$result,&$searchlevel&=&0)&{&&
&&while(is_array($haystack)&&&&isset($haystack[key($haystack)]))&{
&&&&if($searchlevel&==&0&&&&key($haystack)&==&$key&&&&$haystack[$key]&==&$needle)&{
&&&&&&$result&=&$haystack;
&&&&}&elseif($searchlevel&&&0)&{
&&&&&&array_search_in_level($needle,&$haystack[key($haystack)],&$key,&$result,&$searchlevel&-&1);
&&&&}
&&&&next($haystack);
&&}
}
?&
1.&2-dimensional&array,&search&by&both&key&and&value
$arr1&=&array(
&&1&=&&array('id'&=&&1,&'name'&=&&'Alex',&'gender'&=&&'male'),
&&...
&&12&=&&array('id'&=&&12,&'name'&=&&'John',&'gender'&=&&'male'),
);
&?php&array_search_in_level('John',&$arr1,&'name',&$result,&1);&?&
$result&is:
array(
&&'id'&=&&int&12
&&'name'&=&&string&'John'&(length=4)
&&'gender'&=&&string&'male'&(length=4)
)
2.&3-dimensional&array,&search&by&value&only:
&?php
$arr2&=&array(
&&1&=&&array('id'&=&&1,&'name'&=&&'Alex',&'gender'&=&&'male'),
&&/*&...&*/
&&12&=&&array('id'&=&&12,&'name'&=&&'John',&'gender'&=&&'male',&'friends'&=&&array('Helen',&'Julia')),
);
array_search_in_level('Helen',&$arr1,&0,&$result,&2);
?&
$result&is:
array(
&&0&=&&string&'Helen'&(length=5)
&&1&=&&string&'Julia'&(length=5)
)
If&you&wish&to&search&a&multidimensional&array&by&keys:&?phpfunction&extract_values_by_key&(&$array,&$needle_key,&&$out&=&array&()&)&{&&&&foreach&(&(array)&$array&as&$key&=&&$value&)&{&&&&&&&&if&(&!&is_array&(&$value&)&&&&$key&==&$needle_key&)&{&&&&&&&&&&&&array_push&(&$out,&$value&);&&&&&&&&}&&&&&&&&else&{&&&&&&&&&&&&extract_values_by_key&(&$value,&$needle_key,&&$out&);&&&&&&&&}&&&&}&&&&return&$out;}?&
This&is&how&to&search&a&part&of&a&val&in&an&array&:
&?php
&&&&&&function&array_ereg_search($val,&$array)&{
&&&&&&&&&&
&&&&&&&&&&$i&=&0;
&&&&&&&&&&$return&=&array();
&&&&&&&&&&
&&&&&&&&&&foreach($array&as&$v)&{
&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&if(eregi($val,&$v))&$return[]&=&$i;
&&&&&&&&&&&&&&&$i++;
&&&&&&&&&&&&&&&
&&&&&&&&&&}
&&&&&&&&&&
&&&&&&return&$return;
&&&&&&
&&&&&&}
?&
Incidentally,&the&KeyCompare()&function&I&described&above&is&a&generalized&version.&Since&array_bsearch()&doesn't&care&about&specific&return&values,&just&greater&then,&less&than,&or&equal&to&zero,&when&you&are&comparing&two&numbers&you&can&greatly&simplify&the&comparison&function&to&something&like:&?php&&function&KeyCompare(&$obj,&$needle&)&{&&&&&&return&$obj['my_key']&-&$needle;&&}?&
As&others&have&noted,&if&your&array&is&already&sorted,&a&binary&search&is&the&way&to&go.&When&I&realized&PHP&doesn't&have&a&native&one,&I&came&here&to&see&what&others&had&done&to&implement&this&workhorse&algorithm.&While&I&appreciate&those&that&have&posted&their&own&solutions&here,&none&of&those&implementations&met&my&needs.&Also,&due&mainly&to&non-optimal&loop&processing,&the&code&offered&required&extra&post-processing&to&handle&various&ways&the&search&loop&may&have&exited.&Proper&coding&of&initial&conditions&and&the&main&loop&eliminates&this&extra&processing.Also,&the&solutions&presented&assumed&a&simple&one-dimensional&array&and&basic&comparisons.&I&needed&to&search&an&array&of&user&objects,&with&the&comparison&performed&on&one&of&the&object&attributes.&C/C++&handles&the&need&for&comparison&flexibility&by&the&binary&search&function&taking&a&parameter&that&points&to&a&user&function&that&performs&any&arbitrarily&complex&comparison&and&returns&a&defined&result&depending&on&the&relative&magnitudes&of&the&compared&entities.&Since&PHP&allows&similar&function&reference&parameters,&I&realised&it&would&be&quite&easy&to&implement&this&functionality.I&won't&go&into&an&explanation&of&the&algorithm&chosen&for&the&main&binary&search&function,&google&"binary&searches"&if&you&don't&understand&how&they&work.&I&will&mention&however&that&the&ONLY&way&to&exit&the&main&loop&in&this&function&is&on&a&match,&or&a&definite&fail.&The&loop&will&never&terminate&while&the&result&of&the&search&is&indeterminate.Some&solutions&I've&seen&here&and&elsewhere&return&the&index&of&the&found&element&on&a&match,&and&"false"&on&a&fail.&Since&PHP&treats&a&zero&the&same&as&false&in&expressions,&and&zero&is&a&valid&array&index,&using&false&to&designate&"not&found"&gives&an&ambiguous&result&in&some&cases.&I&chose&to&use&the&value&-1&to&signify&a&search&failure&instead.&&?php&&&&function&array_bsearch(&$needle,&$haystack,&$comparator&)&{&&&&&&&&$high&=&Count(&$haystack&)&-1;&&&&&&&&$low&=&0;&&&&&&&&&&&&&&&&while&(&$high&&=&$low&){&&&&&&&&&&&&$probe&=&Floor(&(&$high&+&$low&)&/&2&);&&&&&&&&&&&&$comparison&=&$comparator(&$haystack[$probe],&$needle&);&&&&&&&&&&&&if&(&$comparison&&&0&)&{&&&&&&&&&&&&&&&&$low&=&$probe&+1;&&&&&&&&&&&&}&elseif&(&$comparison&&&0&)&{&&&&&&&&&&&&&&&&$high&=&$probe&-1;&&&&&&&&&&&&}&else&{&&&&&&&&&&&&&&&&return&$probe;&&&&&&&&&&&&}&&&&&&&&}&&&&&&&&&&&&//&---The&loop&ended&without&a&match&&&&&&return&-1;&&&&}?&In&this&function&the&parameters&"$needle"&and&"$haystack"&have&the&same&meaning&as&for&the&native&array_search()&PHP&function.&The&third&parameter,&"$comparator"&is&the&name&of&the&function&to&use&to&determine&if&an&array&element&matches&the&needle.The&array_bsearch()&function&is&self-contained,&and&doesn't&need&modification&no&matter&how&complex&the&comparison&needs&to&be.&The&actual&comparison&is&performed&by&a&purpose-written&user&function&that&takes&two&parameters&and&returns&a&numerical&result.&array_bsearch()&will&call&this&function&each&time&it&needs&to&compare&an&array&element&to&the&needle.&The&first&parameter&passed&will&be&the&element&to&test,&and&the&second&will&the&the&needle&value&passed&to&array_bsearch().&Note&that&if&you&will&always&search&for&the&same&thing&your&user&function&can&ignore&the&second&parameter&and&hard-code&the&test&on&the&first&parameter.The&comparison&user&function&must&return&a&positive&number&if&the&element&is&greater&than&the&needle,&a&negative&number&if&it&is&smaller&than&the&needle,&and&zero&if&they&match.Given&a&scenario&where&you&want&to&find&the&index&of&a&user&object&loaded&from&MySQL&in&an&array,&where&the&"my_key"&property&equals&54.&Here's&how&you&could&code&it&using&a&user&function&and&the&new&array_bsearch()&function.&?php&&function&KeyCompare(&$obj,&$needle&)&{&&&&&&if&(&$obj['my_key']&&&$needle&)&{&&&&&&&&&&return&-1;&&&&&&}&elseif&(&$obj['my_key']&&&$needle&)&{&&&&&&&&&&return&1;&&&&&&}&else&{&&&&&&&&&&return&0;&&&&&&}&&}&&$index&=&array_bsearch(&54,&$my_array,&'KeyCompare'&);?&Hope&this&is&helpful&to&somebody&out&there.
I&made&this&function&after&I&didnt&find&a&recursive&array_search&function&with&a&limit&and&the&possibility&to&inverse&the&search.&So&here&is&it:&?phpfunction&search_in_array&($needle,&$haystack,&$inverse&=&false,&$limit&=&1)&{&&&&&&&&#&Settings&&&&$path&=&array&();&&&&$count&=&0;&&&&&&&&#&Check&if&inverse&&&&if&($inverse&==&true)&&&&&&&&$haystack&=&array_reverse&($haystack,&true);&&&&&&&&&&&&#&Loop&&&&foreach&($haystack&as&$key&=&&$value)&{&&&&&&&&#&Check&for&return&&&&&&&&if&($count&&&0&&&&$count&==&$limit)&&&&&&&&&&&&&&&&return&$path;&&&&&&&&&&&&&&&&#&Check&for&val&&&&&&&&if&($value&===&$needle)&{&&&&&&&&&&&&&&&&&&&&&&&&#&Add&to&path&&&&&&&&&&&&$path[]&=&$key;&&&&&&&&&&&&&&&&&&&&&&&&#&Count&&&&&&&&&&&&$count++;&&&&&&&&&&&&&&&&&&&&}&else&if&(is_array&($value))&{&&&&&&&&&&&&&&&&&&&&&&&&#&Fetch&subs&&&&&&&&&&&&$sub&=&search_in_array&($needle,&$value,&$inverse,&$limit);&&&&&&&&&&&&&&&&&&&&&&&&#&Check&if&there&are&subs&&&&&&&&&&&&if&(count&($sub)&&&0)&{&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&#&Add&to&path&&&&&&&&&&&&&&&&$path[$key]&=&$sub;&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&#&Add&to&count&&&&&&&&&&&&&&&&$count&+=&count&($sub);&&&&&&&&&&&&}&&&&&&&&}&&&&}&&&&&&&&return&$path;}?&
I&was&trying&to&use&array_search&to&retrieve&all&the&values&that&match&a&given&needle,&but&it&turns&out&only&the&first&match&key&is&returned.&I&built&this&little&function,&which&works&just&like&array_search,&but&returns&all&the&keys&that&match&a&given&needle&instead.&The&output&is&an&array.&?php$haystack&=&array('a','b','a','b');$needle&=&'a';print_r(array_search_all($needle,&$haystack));//Output&will&be//&Array//&(//&&&&&&&&&[0]=&1//&&&&&&&&&[1]=&3//&)function&array_search_all($needle,&$haystack){#array_search_match($needle,&$haystack)&returns&all&the&keys&of&the&values&that&match&$needle&in&$haystack&&&&foreach&($haystack&as&$k=&$v)&{&&&&&&&&&&&&if($haystack[$k]==$needle){&&&&&&&&&&&&&&&&&&&$array[]&=&$k;&&&&&&&&}&&&&}&&&&return&($array);&&&&}?&
A&slight&addition&to&array_search_recursive&by&Alireza&Eliaderani&below.&&The&original&searched&the&entire&haystack,&even&if&it&found&the&needle&at&the&beginning&of&the&haystack.&I&must&admit&I&had&a&little&trouble&wrapping&my&head&around&how&to&break&out&of&a&loop&in&a&recursive&function.&&This&version&returns&after&first&occurrence&of&needle.&changes&commented.&?phpfunction&array_search_recursive($needle,&$haystack){&&&&$path=array();&&&&foreach($haystack&as&$id&=&&$val)&&&&{&&&&&&&&&&if($val&===&$needle)&{&&&&&&&&&&&&&&$path[]=$id;&&&&&&&&&&&&&&&&&&&&&&&&&&&#&^^this&breaks&out&of&loop&when&it&finds&needle&&&&&&&&&}&else&if(is_array($val)){&&&&&&&&&&&&&$found=array_search_recursive($needle,&$val);&&&&&&&&&&&&&&if(count($found)&0){&&&&&&&&&&&&&&&&&&$path[$id]=$found;&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&#&^^this&breaks&out&of&loop&when&recursive&call&found&needle&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&}&&&&&&}&&&&&&return&$path;}?&
Expanding&on&the&comment&by&hansen{}cointel.de:When&searching&for&a&string&and&the&array&contains&0&(zero),&the&string&is&casted&to&(int)&by&the&type-casting&which&is&always&0&(perhaps&the&opposite&is&the&proper&behaviour,&the&array&value&0&should&have&been&casted&to&string).&That&produces&unexpected&results&if&strict&comparison&is&not&used:&?php$a&=&array(0,&"str1",&"str2",&"str3");echo&"str1&=&".array_search("str1",&$a).",str2&=&".array_search("str2",&$a).",str3&=&".array_search("str3",&$a).",str1&strict&=&".array_search("str1",&$a,&true).",str2&strict&=&".array_search("str2",&$a,&true).",str3&strict&=&".array_search("str3",&$a,&true);?&This&will&return:str1&=&0,&str2&=&0,&str3&=&0,&str1&strict&=&1,&str2&strict&=&2,&str3&strict&=&3
This&function&can&search&for&an&array&or&string&within&an&array.&?phpfunction&array_search_array($needle,&$haystack){&&&&if(is_array($needle)&&&&is_array($haystack))&{&&&&&&&&&$tmp&=&array_diff_assoc($needle,&$haystack);&&&&&&&&if(empty($tmp))&return&true;&&&&&&&&foreach($haystack&as&$value)&{&&&&&&&&&&&&if(is_array($value))&{&&&&&&&&&&&&&&&&$tmp&=&array_diff_assoc($needle,&$value);&&&&&&&&&&&&&&&&if(empty($tmp))&return&true;&&&&&&&&&&&&}&&&&&&&&}&&&&}&&&&if(is_array($haystack)&&&&!is_array($needle))&{&&&&&&&&foreach($haystack&as&$value)&{&&&&&&&&&&&&if(is_array($value))&{&&&&&&&&&&&&&&&&$tmp&=&array_diff_assoc($needle,&$value);&&&&&&&&&&&&&&&&if(empty($tmp))&return&true;&&&&&&&&&&&&}&elseif($needle&==&$value)&return&true;&&&&&&&&}&&&&}&elseif($needle&==&$haystack)&return&true;&&&&return&false;}?&It's&not&recursive&yet,&so&please&improve&it&if&you&feel&for&it&;)
this&function&return&a&multidimensional&path&of&recursively&founded&$needle&in&a&multidimensional&$haystack&?phpfunction&array_search_recursive($needle,&$haystack){&&&&$path=array();&&&&foreach($haystack&as&$id&=&&$val)&&&&{&&&&&&&&&&if($val&===&$needle)&&&&&&&&&&&&&&$path[]=$id;&&&&&&&&&else&if(is_array($val)){&&&&&&&&&&&&&$found=array_search_recursive($needle,&$val);&&&&&&&&&&&&&&if(count($found)&0){&&&&&&&&&&&&&&&&&&$path[$id]=$found;&&&&&&&&&&&&&&}&&&&&&&&&&&&&&&&&}&&&&&&}&&&&&&return&$path;}?&
If&you&exit&the&function&whith&"return",&there&is&no&need&to&break&;)i&would&write&it&like&this:&?phpfunction&array_search_recursive($needle,&$haystack,&$path=array()){&&&&foreach($haystack&as&$id&=&&$val)&&&&{&&&&&&&&&$path2=$path;&&&&&&&&&$path2[]&=&$id;&&&&&&&&&&if($val&===&$needle)&&&&&&&&&&&&&&return&$path2;&&&&&&&&&else&if(is_array($val))&&&&&&&&&&&&&&if($ret&=&array_search_recursive($needle,&$val,&$path2))&&&&&&&&&&&&&&&&&&&return&$ret;&&&&&&}&&&&&&return&false;}&$array&=&array(&&&"a"&=&&array(&&&&&&&"b"&=&&array("c"),&&&&&&&"d"&=&&array("e"),&&&&&&&),&&&&"f"&=&&array(&"g",&"h"),&&&&);&var_dump(array_search_recursive("e",&$array));?&var&dump&prints&a&array:&(a,&d,&0)
I&wrote&a&better&array_search_recursive&function.&&The&other&functions&listed&work&and&will&evaluate&to&true,&however,&they&loop&through&the&stack&even&after&the&needle&is&found:&so&this&function&will&take&the&overhead&off&the&cpu&=P&?php&&function&array_search_recursive($needle,&$haystack)&&{&&&&&&&&&foreach&($haystack&as&$k&=&&$v)&&&&{&&&&&&for&($i=0;&$i&count($v);&$i++)&&&&&&&&if&($v[$i]&===&$needle)&&&&&&&&{&&&&&&&&&&return&true;&&&&&&&&&&&&&&&&&&}&&&&&}&&}&&$access['admin']&=&array('nick1');&&$access['voice']&=&array('nick2',&'nick3');&&if&(array_search_recursive('nick3',&$access))&&&&echo&'yes';&&print_r($access);?&I&wrote&this&for&an&access&list&that&I&have&implemented&into&an&IRC&bot.&&See&more&interesting&stuff&at&dreamevilconcept's&forum.
Simple&way&to&get&variable&name&by&using&array_search&function:&?phpfunction&varname($var){&&&&return&(isset($var))?&array_search($var,&$GLOBALS)&:&false;}$boogie&=&'tonight';echo&varname($boogie);?&
Combining&syntax&of&array_search()&and&functionality&of&array_keys()&to&get&all&key=&value&associations&of&an&array&with&the&given&search-value:&?phpfunction&array_search_values(&$m_needle,&$a_haystack,&$b_strict&=&false){&&&&return&array_intersect_key(&$a_haystack,&array_flip(&array_keys(&$a_haystack,&$m_needle,&$b_strict)));}?&Usage:&?php$array1&=&array(&'pre'=&'2',&1,&2,&3,&'1',&'2',&'3',&'post'=&2);print_r(&array_search_values(&'2',&$array1));print_r(&array_search_values(&'2',&$array1,&true));print_r(&array_search_values(&2,&$array1,&true));?&Will&return:array(4)&{&&&&["pre"]&=&&&&&string(1)&"2"&&&&[1]&=&&&&&int(2)&&&&[4]&=&&&&&string(1)&"2"&&&&["post"]&=&&&&&int(2)}array(2)&{&&&&["pre"]&=&&&&&string(1)&"2"&&&&[4]&=&&&&&string(1)&"2"}array(2)&{&&&&[1]&=&&&&&int(2)&&&&["post"]&=&&&&&int(2)}
This&is&the&phpfied&version&of&the&array_search&function&for&PHP&version&under&4.0.5&?phpif(!function_exists("array_search")){&&&&function&array_search(&$needle,&$haystack,&$strict&=&FALSE&){&&&&&&&&if(&!is_array($haystack)&)return&FALSE;&&&&&&&&foreach($haystack&as&$key&=&&$val){&&&&&&&&&&&&if(&&&(&&(&$strict&)&&&&(&$needle&===&$val&)&&)&||&(&&(&!$strict&)&&&&(&$needle&==&$val&)&&)&&&)return&$key;&&&&&&&&}&&&&&&&&return&FALSE;&&&&}/*&endfunction&array_search&*/}/*&endfunction&exists&array_search*/?&
Hi!&Based&on&Chris&function,&I&made&another&to&simplify&code&and&improve&diferents&features...With&this&function&you&can:-&Filter&Key&and&Values&recursively-&Call&function&many&times&using&previows&result-&Final&result&always&will&be&an&array&numeric&index&contenting&a&value&or&sigle&array&key=&value.Thanks&for&PHP!&?phpfunction&array_search_recursive($needle,&$haystack,&$nodes=array()){&&&&&&&&foreach&($haystack&as&$key1=&$value1)&&&{&&&&if&(is_array($value1))&&&&&&$nodes&=&array_search_recursive($needle,&$value1,&$nodes);&&&elseif&(($key1&==&$needle)&or&($value1&==&$needle))&&&&&&$nodes[]&=&array($key1=&$value1);&&}&&&return&$nodes;}&&&&$arg[]&=&array("column1"=&"Class3");$arg[]&=&array("column2"=&"Class1");$arg[]&=&array("column3"=&"Class3");$arg[]&=&array("column4"=&"Class4");$arg[]&=&array("column4"=&"Class3");$arg[]&=&"column3";&&&&$filter&=&array_search_recursive("Class3",$arg);echo&"&hr&";var_dump($filter);&&&&$filter&=&array_search_recursive("column3",$filter);echo&"&hr&";var_dump($filter);?&
MultiArray&find&function.
After&some&time&unsuccessful&looking&for&algorithm&to&find&a&string&in&multidimensional&array&I&wrote&one:
&?php
function&multidimArrayLocate($array,&$text){
&&foreach($array&as&$key&=&&$arrayValue){
&&&&if&(is_array($arrayValue)){
&&&&&&if&($key&==&$text)&$arrayResult[$key]&=&$arrayValue;
&&&&&&$temp[$key]&=&multidimArrayLocate($arrayValue,&$text);
&&&&&&if&($temp[$key])&$arrayResult[$key]&=&$temp[$key];
&&&&}
&&&&else{
&&&&&&if&($key&==&$text)&$arrayResult[$key]&=&$arrayValue;
&&&&}
&&}
&&return&$arrayResult;
}
?&
Just&adding&my&two&penneth&to&someone&else's&script&from&below.&If&you&need&to&easily&index&your&csv&use&this&slightly&modified&script&to&parse&a&csv&file&into&an&associative&array&2d,&indexed&by&the&first&column&value
&?php
function&buildStock($File)&{
&&&&&&&&$handle&=&fopen($File,&"r");
&&&&&&&&$fields&=&fgetcsv($handle,&1000,&",");
&&&&&&&&while($data&=&fgetcsv($handle,&1000,&","))&{
&&&&&&&&&&&&$detail[]&=&$data;
&&&&&&&&}
&&&&&&&&echo&"details";
&&&&&&&&var_dump($detail);
&&&&&&&&echo&"&br&/&";
&&&&&&&&$x&=&0;
&&&&&&&&$y&=&0;
&&&&&&&&foreach($detail&as&$i)&{
&&&&&&&&&&&&foreach($fields&as&$z)&{
&&&&&&&&&&&&&&&&//original&code
&&&&&&&&&&&&&&&&//$stock[$x][$z]&=&$i[$y];
&&&&&&&&&&&&&&&&$stock[$i['0']][$z]&=&$i[$y];
&&&&&&&&&&&&&&&&$y++;
&&&&&&&&&&&&}
&&&&&&&&&&&&$y&=&0;
&&&&&&&&&&&&$x++;
&&&&&&&&}
&&&&&&&&return&$stock;
&&&&}
var_dump(buildStock("conf.csv"));
?&
Make&a&recursive&search&on&array&and&return&the&matches&elements&in&the&same&structure&than&the&original&array&and&unset&empty&arrays:
&?php
function&array_search_recursive($needle,&$haystack,&$tree=Array(),$index=""){
&&&&&&&&if&(is_array($haystack)){
&&&&&&&&&&&&if&(count($tree)==0)&$tree=array_merge(Array(),$haystack);
&&&&&&&&&&&&foreach($haystack&as&$k=&$current){
&&&&&&&&&&&&&&&&if&(is_array($current)){
&&&&&&&&&&&&&&&&&&&&array_search_recursive($needle,$current,$tree,$index."[$k]");
&&&&&&&&&&&&&&&&&&&&eval

我要回帖

更多关于 php删除数组指定元素 的文章

 

随机推荐