[英]Searching for a substring inside an array in php
嗨,我想知道是否有一種好的算法來搜索另一個數組內部的數組內的子字符串,
我有類似的東西:
數組(
[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=""
)
)
我想做的就是知道目標的位置,例如[0] [4],但並不總是相同
我現在正在做的是在另一個內部進行一會兒,並檢查是否有子字符串的strpos,但是也許有更好的方法來執行此操作,有什么建議嗎?
謝謝你所做的一切
更新的代碼:
$ 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; } } }
在這里嘗試此代碼,您將獲得字符串的完整信息。 $ find是您的子字符串。 $ data是您的數組。
$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];
嗯,也許像:
foreach($outsideArray as $outterKey=>$outter) {
foreach($outter as $innerKey=>$inner){
if(substr_count ($inner , $needle)) {
echo $outterKey . " and " . $innerKey;
}
}
}
編輯:可擴展,我在您的評論中注意到您希望它可擴展。 遞歸如何?
function arraySearch($array) {
foreach($array as $key=>$item){
if(is_array($item)
return arraySearch($item);
elseif(substr_count ($item , $needle)
return $key;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.