null, "price" => [ "height" => 0.009897490279-6ren">
gpt4 book ai didi

PHP-获取在多个索引中具有值的键

转载 作者:行者123 更新时间:2023-12-02 02:41:51 26 4
gpt4 key购买 nike

我有以下数组:

$myArray = [
[
"name" => null,
"price" => [
"height" => 0.0098974902792506,
"left" => 0.8385,
"page" => 1,
"top" => 0.51290208554259,
"width" => 0.0275,
],
],
[
"name" => null
"price" => [
"height" => 0.0098974902792506,
"left" => 0.838,
"page" => 1,
"top" => 0.56981265464829,
"width" => 0.028,
]
],
[
"name" => null
"price" => [
"height" => 0.010250972074938,
"left" => 0.5905,
"page" => 1,
"top" => 0.44114528101803,
"width" => 0.0285,
]
]
];

我正在尝试检查数组并获取每个数组中具有值(不是null)的的名称。在上面的示例中,这将是价格

但是,数组也可以如下所示:

[
[
"name" => null,
"price" => [
"height" => 0.0098974902792506,
"left" => 0.8385,
"page" => 1,
"top" => 0.51290208554259,
"width" => 0.0275,
],
],
[
"name" => null
"price" => null
],
[
"name" => null
"price" => null
]
]

在这种情况下,没有一个数组键在所有数组中都有值。

以下是我实现此目标的尝试:

$originalKeyWithValue = null;
foreach($myArray as $key => $item)
{

$originalKeyWithValue = array_key_first($item);
if (isset($myArray[$key+1])) {
$nextKeyWithValue = array_key_first($myArray[$key+1]);

if($originalKeyWithValue != $nextKeyWithValue){
$originalKeyWithValue = $nextKeyWithValue;
}

}
}
return $originalKeyWithValue;

然而,上面的代码返回 name 作为键,即使它在 $myArray 中的所有数组中都是 null

最佳答案

这就是我要做的:

// I take first element of array as a source for indexes
foreach ($myArray[0] as $index => $item) {
// next I extract all elements from all subarrays under current `$index`
$values = array_column($myArray, $index);
// then I filter values to remove nulls.
// This also removes 0, empty arrays, false,
// so maybe you should change filter process
$values_filtered = array_filter($values);
// if number of filtered items is same as in original array - no nulls found
if (count($values_filtered) === count($values)) {
echo $index;
// optionally
// break;
}
}

关于PHP-获取在多个索引中具有值的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63463989/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com