簡體   English   中英

PHP 將逗號分隔的字符串與數組值匹配,但順序不同

[英]PHP match comma separated string with array value but not in exact order

我有一個可能很簡單的查詢,但在任何地方都找不到確切的解決方案。

有一個逗號分隔的字符串,例如1,3和一個數組,其值例如1,3,2 OR 3,1,4 我需要一個函數,當我嘗試在數組中搜索此字符串時,它為兩個記錄返回 TRUE,因為數字 1 和 3 存在於兩個數組值中,但順序不同。

我已經嘗試使用array_searchstrpos甚至explode ,首先使陣列中的字符串,然后array_intersect相交兩個陣列希望得到一個積極的比賽,但總是只返回其值1,3,2,而不是3,1陣列, 4.

任何建議或指示都會非常有幫助。

提前謝謝了。

======================

PS:這是我的代碼

        //Enter your code here, enjoy!
$st_array = array();
$st_data1['id'] = 1;
$st_data1['title'] = 'Jane doe';
$st_data1['disk'] = '1,3,2';
array_push($st_array, $st_data1);

$rc_disk_id = '1,3';

$st_data2['id'] = 2;
$st_data2['title'] = 'Jane Smith';
$st_data2['disk'] = '3,1,4';
array_push($st_array, $st_data2);


foreach($st_array as $st_data) {
    $rc_disk_ids = explode(",",$rc_disk_id);
    $match = array_intersect($rc_disk_ids, $st_data);
    if (!empty($match)) {
        echo "\nFound\n";
        print_r($st_data);
    }
    else {
        echo "Nope!";
    }
}

您的代碼非常接近。 您還需要explode磁盤ID列表在$st_data ,然后用array_diff檢查所有的值是否$rc_disk_ids出現在該列表:

foreach($st_array as $st_data) {
    $rc_disk_ids = explode(",",$rc_disk_id);
    $st_disk_ids = explode(',', $st_data['disk']);
    $match = array_diff($rc_disk_ids, $st_disk_ids);
    if (empty($match)) {
        echo "\nFound\n";
        print_r($st_data);
    }
    else {
        echo "Nope!";
    }
}

示例數據的輸出:

Found
Array
(
    [id] => 1
    [title] => Jane doe
    [disk] => 1,3,2
)

Found
Array
(
    [id] => 2
    [title] => Jane Smith
    [disk] => 3,1,4
)

3v4l.org 上的演示

也許您可以嘗試搜索字符串而不是比較數組。

$strArr = explode(",", "1,3");
$arrToBeSearched = ["1", "3", "2"];

foreach($strArr as $val){
    if(!in_array($val, $arrToBeSearched)){
        return FALSE;
    }
}

// If it reaches here, then all values in 
//the $strArr where found in the 
//$arrToBeSearched
return TRUE;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM