在多维大海捞针中定位针并从其父级返回值

问题描述 投票:0回答:1

我需要在多维数组中搜索值

IMPORTANT
,然后从其父数组中获取其
startIndex
endIndex

[0] => Array
                                (
                                    [startIndex] => 1
                                    [endIndex] => 10
                                    [textRun] => Array
                                        (
                                            [content] => IMPORTANT
                                            [textStyle] => Array
                                                (
)
)
)
php arrays multidimensional-array filtering
1个回答
1
投票

如果我理解正确,你的输入数组是这样的:

$arr = [
    [
        'startIndex' => 1,
        'endIndex' => 2,
        'textRun' => [
            'content' => 'unimportant',
            'textStyle' => [],
        ],
    ],
    [
        'startIndex' => 1,
        'endIndex' => 10,
        'textRun' => [
            'content' => 'IMPORTANT',
            'textStyle' => [],
        ],
    ],
    [
        'startIndex' => 3,
        'endIndex' => 18,
        'textRun' => [
            'content' => 'unimportant',
            'textStyle' => [],
        ],
    ],
];

您应该能够使用

content
:
 将这个数组减少为包含 
IMPORTANT
 等于 
array_filter()

的元素
// search for 'IMPORTANT'
$matches = array_filter($arr, function ($v) {
    return isset($v['textRun']['content']) && ($v['textRun']['content'] == 'IMPORTANT');
});

if ($matches) {

    // first match
    $match = reset($matches);
    $startIndex = $match['startIndex'];
    $endIndex = $match['endIndex'];

    // ...
    var_dump($startIndex, $endIndex);
}

结果:

int(1)
int(10)
© www.soinside.com 2019 - 2024. All rights reserved.