Searching for a substring inside an array in php
Hi I would like to know if there is a good algorithm to the search of a substring inside an array that is inside another array,
I have something like:
Array(
[0] => Array(
[0] => img src="开发者_如何学运维1" />
[1] => img src="2" alt="" class="logo i-dd-logo" />
[2] => img src="3" alt="" />
[3] => img src="4" width="21" height="21" alt="" class="i-twitter-xs" />
[4] => img src="myTarget" width="21" height="21" alt="" class="i-rss" />
[5] => <img class="offerimage" id="product-image" src="6" title="" alt=""/>
[6] => <img class="offerimage" id="product-image" src="7" title="" alt=""/>
[7] => <img class="offerimage" id="product-image" src="8" title="" alt=""/>
[8] => <img src="9" width="16" height="16" />
)
[1] => Array(
[0] => src="1"
[1] => src="a" alt="" class="logo i-dd-logo"
[2] => src="b" alt=""
)
)
What I want to do is to know the position of target, for example [0][4] but it's not always the same
What I'm doing now is a while inside another while and checking whith strpos for the substring, but maybe there is a better way to do this, any suggestions?
Thanks for everything
Updated code:
$i=-1;
foreach($img as$outterKey=>$outter) {
foreach($outter as $innerKey=>$inner){ $pos = strpos($img[$outterKey][$innerKey],"myTarget"); if (!$pos === false) { $i=$outterKey;$j=$innerKey; break 2; } } }
Umm, maybe like:
foreach($outsideArray as $outterKey=>$outter) {
foreach($outter as $innerKey=>$inner){
if(substr_count ($inner , $needle)) {
echo $outterKey . " and " . $innerKey;
}
}
}
EDIT: Scalable, I noticed in your comments you want it scalable. How about recursive?
function arraySearch($array) {
foreach($array as $key=>$item){
if(is_array($item)
return arraySearch($item);
elseif(substr_count ($item , $needle)
return $key;
}
}
try this code here you got the complete posistion of your string. here $find is your substring. $data is your array.
$find = "<img src='4' width='21' height='21' alt=' class='i-twitter-xs' />";
foreach ($data as $out_key => $out_value)
{
if(is_array($out_value))
{
if(in_array($find, $out_value))
{
$out_pos = array_search($out_value, $data);
$inn_pos =array_search($find, $out_value);
}
}
}
echo $data[$out_pos][$inn_pos];
精彩评论