是否有一种干净优雅的方法来检查具有特定值的数组对象值" positionID = string(29)"如果它的"行动"从例如"(字符串)1&#34开始;并以"(字符串)0"结束。
unlooped数组看起来类似于
array (
[0] => Object1 {
['PositionID'] => (string) 29
['Action'] => (string) 1
}
[1] => Object22 {
['PositionID'] => (string) 30
['Action'] => (string) 0
}
[2] => Object23 {
['PositionID'] => (string) 29
['Action'] => (string) 1
}
[3] => Object5 {
['PositionID'] => (string) 31
['Action'] => (string) 0
}
[2] => Object23 {
['PositionID'] => (string) 29
['Action'] => (string) 0
}
);
我想在那个数组中找出最后一个" Action"出现" positionID = 29"是0或其他。目前我正在将positionId分组并将它们存储到第三个数组并循环它,这对我来说就像一个肮脏的解决方案。
答案 0 :(得分:1)
看看end()
。第一项应该是显而易见的。
$first = $array[0];
if ($first->positionId === '29' && $first->Action === '1') {
$last = end($array);
if ($last->positionId === '29' && $last->Action === '0' {
// Stuff
}
}
答案 1 :(得分:0)
<?php
$items =
[
[
'position' => '17',
'action' => '1'
],
[
'position' => '47',
'action' => '0'
],
[
'position' => '23',
'action' => '0'
]
];
foreach ($items as $k => $item)
$items[$k] = (object) $item;
var_dump($items);
if(array_column($items, 'action', 'position')[23] === '0')
echo "Action is '0' for the object with position 23";
输出:
array(3) {
[0]=>
object(stdClass)#1 (2) {
["position"]=>
string(2) "17"
["action"]=>
string(1) "1"
}
[1]=>
object(stdClass)#2 (2) {
["position"]=>
string(2) "47"
["action"]=>
string(1) "0"
}
[2]=>
object(stdClass)#3 (2) {
["position"]=>
string(2) "23"
["action"]=>
string(1) "0"
}
}
Action is '0' for the object with position 23
答案 2 :(得分:0)
您可以使用array_column和array_filter以及end的组合来返回数组$result
中的最后一项:
$result = array_column(array_filter($arrays, function ($x) {
return $x->PositionID === '29';
}), 'Action');
$lastValue = end($result);
var_dump($lastValue);
那会给你:
string(1) "0"
然后你可以使用它:
if ($lastValue === "0") {
// ...
}