且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

根据属性值有效地查找嵌套的PHP数组元素

更新时间:2023-11-28 08:00:52

这取决于您要除了找到价值之外还可以做

array_filter 很简单,但是它将遍历整个数组。

array_filter is simple, but it will loop through the whole array.

array_search 看起来更快,但是它需要复制源数组,因此实际上是 array_filter 慢(不是很多)。

array_search on a reduced set looks faster, but it needs to make a copy of the source array, so it's actually slower than array_filter (not by much).

foreach 解决方案不会创建额外的数组,它使您无法进行查找:

The foreach solution you tried first will not create extra arrays and it allows you to break on a find:

foreach($array as $nestedArray) {
    if ($nestedArray['key'] == 'material') {
        $material = $nestedArray['value'];
        break; // <--- found!
    }
}

所以在短数组上,我会接受使用 array_column 的解决方案,或者如果您确定材料在那里,则可以进行以下 array_column 调整:

So on short arrays I'd go with the accepted solution using array_column, or if you're sure that the material is there, there is this array_column tweak:

// Transform the records into keypairs
$keypairs = array_column($records, 'value', 'key');

现在的密钥对是[width => 900,material => paper,...],所以:

Now keypairs is [ width => 900, material => paper, ... ], so:

$material = $keypairs['material'];

我要添加 array_key_exists 确定。这样可以节省 array_search (不是一个很大的优势,但是您可能会使用keypair对象)。

I'd add a array_key_exists just to be sure. This saves the array_search (not that great an advantage, but you might have a use for the keypair object).

如果您只需要一个值而不需要其他任何内容,那么性能就非常重要,并且数组很大,那么我不会放弃在JSON内将' material:'作为字符串使用 strpos ,即使它是代码气味。

If you need exactly that one value and nothing else, performance is at a premium, and the array is large, I'd not throw out the idea of looking for '"material":"' inside the JSON as a string with strpos, even if it's a code smell.