php 数组匹配结果

wlsrxk51  于 2023-03-11  发布在  PHP
关注(0)|答案(2)|浏览(211)

当var_dump($haystack)的结果如下所示时,如何匹配前面的value/text Trykk

array(2) {
    [0] => array(11) {
        ["id"] => string(13) "64085aafcb9db"
        ["type"] => string(10) "checkboxes"
        ["raw"] => array(1) {
            [2] => string(5) "b3ygo"
        }
        ["values"] => array(1) {
            [0] => array(6) {
                ["label"] => string(11) "Trykk front"
                ["price"] => float(42)
                ["price_type"] => string(2) "qt"
                ["slug"] => string(5) "b3ygo"
                ["calc_price"] => float(42)
                ["pricing_hint"] => string(23) "(+kr 42)"
            }
        }
        ["clone_type"] => string(0) ""
        ["label"] => string(31) "Ønsker du trykk på produktet?"
        ["hide_cart"] => bool(false)
        ["hide_checkout"] => bool(false)
        ["hide_order"] => bool(false)
        ["clone_idx"] => int(0)
        ["calc_weight"] => bool(false)
    }
    [1] => array(11) {
        ["id"] => string(13) "64085aaf29908"
        ["type"] => string(4) "file"
        ["raw"] => string(0) ""
        ["values"] => array(1) {
            [0]=>array(4) {
                ["label"] => string(0) ""
                ["price"] => int(0)
                ["price_type"] => string(4) "none"
                ["formatted_label"]=>string(31) ""
            }
        }
        ["clone_type"] => string(0) ""
        ["label"] => string(56) "Om du ønsker trykk på produktet laster du opp logo her"
        ["hide_cart"] => bool(false)
        ["hide_checkout"] => bool(false)
        ["hide_order"] => bool(false)
        ["clone_idx"] => int(0)
        ["calc_weight"] => bool(false)
    }
}
$matches  = preg_grep ('/^Trykk front (\w+)/i', $haystack);
irlmq6kh

irlmq6kh1#

您可以像这样使用array_filter

print_r(array_filter($array, function($a){
    return $a['values'][0]['label'] === 'Trykk front';
}));

Fiddle

4xrmg8kj

4xrmg8kj2#

根据var_dump的输出,“Trykk front”来自$haystack[0]['values']。因此,假设您的代码需要如下更新:

$values = $haystack[0]['values'];

foreach ($values as $value) {
    $label = $value['label'];

    if (preg_match('/^Trykk front/i', $label)) {
        // Match found
        echo "Match found: " . $label;
        break;
    }
}

相关问题