注意:未定义的偏移量:10,即使匹配的数组键数量?

时间:2017-10-21 08:15:40

标签: php arrays sorting

我几乎试图将所有返回的值与preg_match_all分开,有3个值。

我们将所有内容都包含在强标记内,将数字放入一个数组,将文本转换为另一个数组,然后强标记之后的所有内容都进入第三个数组,但我不断收到此错误,我不想忽略。

这是通知:Notice: Undefined offset: 10 on line 49,它在代码底部一直是$saveExtra = $matches[2][$key];

$html = "<strong>1 1/4 lb.</strong> any type of fish
<strong>3 tsp.</strong> tarragon
<strong>3 tsp.</strong> tomato sauce
<strong>1 tbsp.</strong> coconut oil
<strong>Pepper and Salt</strong>, it's optional
<strong>2 tbsp.</strong> oil
<strong>1/4 cup</strong> cream
<strong>1/4 tsp.</strong> tarragon
<strong>1/4 tsp.</strong> tomato sauce
<strong>Salt and Pepper</strong>, it's optional too
";
$variations = array('lb', 'tsp', 'tbsp', 'cup');

$setInfo = [];
$arr_amount = [];
$extra_arr = [];
$arr_units = [];

if(preg_match_all("/<(?:strong|b)>(.*)(?:<\/(?:strong|b)>)(.*)/", $html, $matches)) {

    foreach($matches[1] as $amounts){
        preg_match_all("/^(?:[\p{Pd}.\/\s-]*[\d↉½⅓⅔¼¾⅕⅖⅗⅘⅙⅚⅐⅛⅜⅝⅞⅑⅒⅟])+/um", $amounts, $amount);
        preg_match_all('/[a-zA-Z :]+/m', $amounts, $unit);

        foreach($amount[0] as $amount_arr){
            $arr_amount[] = $amount_arr;
        }

        foreach($unit[0] as $units_rr){
            $arr_units[] = trim(strtolower($units_rr));
        }

        $unit_id = array();
        foreach($arr_units as $key => $unit_arr){
            foreach($variations as $unit_var){
                if(strtolower(trim($unit_arr)) == $unit_var){
                    $unit_id[] = $unit_var;
                }
            }

            if(str_word_count($unit_arr) >= 2){
                $arr_amount[$key] = '';
                $unit_id[$key] = '';


                $saveExtra =  $matches[2][$key];
                $matches[2][$key] = $unit_arr . $saveExtra;
            }

        }
    }
}

如果我们print_r($arr_amount, $unit_id, $matches[2]),我们会得到:

Array
(
    [0] => 1 1/4
    [1] => 3
    [2] => 3
    [3] => 1
    [5] => 
    [6] => 2
    [7] => 1/4
    [8] => 1/4
    [9] => 1/4
    [10] => 
)
Array
(
    [0] => lb
    [1] => tsp
    [2] => tsp
    [3] => tbsp
    [5] => 
    [6] => tbsp
    [7] => cup
    [8] => tsp
    [9] => tsp
    [10] => 
)
Array
(
    [0] =>  any type of fish
    [1] =>  tarragon
    [2] =>  tomato sauce
    [3] =>  coconut oil
    [4] => , it's optional
    [5] => pepper and saltpepper and saltpepper and saltpepper and saltpepper and saltpepper and salt oil
    [6] =>  cream
    [7] =>  tarragon
    [8] =>  tomato sauce
    [9] => , it's optional too
    [10] => salt and pepper
)

过去2天我一直在这里,但是当$key与当前迭代匹配时,我无法弄清楚为什么我会继续得到未定义的偏移量。

我已将代码放在eval上,https://eval.in/883856

1 个答案:

答案 0 :(得分:1)

$match中的第三项( $match[2])是一个包含10个项目的数组。 PHP数组具有从零开始的索引。

根据我的观察,某些时候$key等于10

在访问$key中的$match[2]之前添加一个针对此的保护条款:

if($key >= count($matches[2])) continue;