我有一个类似于以下示例的数组。我想回显一个特定的值。现在我正在做的是:
$array[0]->Question
因此,它输出:问题 1
但我不想要这个解决方案。
有没有办法在没有键的情况下回显特定值,例如(它不是解决方案):
$array[]->Field == 'Field1' ? $array[]->Question : '';
请提出解决方案。
谢谢!
[Required] => Array
(
[0] => stdClass Object
(
[Field] => Field1
[Question] => Question1
[DataType] => Boolean
)
[1] => stdClass Object
(
[Field] => Field2
[Question] => Question2
[DataType] => varchar
)
[2] => stdClass Object
(
[Field] => Field3
[Question] => Question3
[DataType] => Boolean
)
[3] => stdClass Object
(
[Field] => Field4
[Question] => Question5
[DataType] => Int
)
)
这与简单的 SQL SELECT
查询基本相同。此函数将提供类似的结果:
function array_select ($array, $searchField, $searchVal, $selectField = '*') {
// Loop the "table" (array)
foreach ($array as $obj) {
// If the "row" (item) is an object, has the field present and the value matches...
if (is_object($obj) && isset($obj->{$searchField}) && $obj->{$searchField} == $searchVal) {
// Return the value of the requested field, or the entire "row" if * was passed
return $selectField == '*' ? $obj : (isset($obj->{$selectField}) ? $obj->{$selectField} : NULL);
} // if
} // foreach
// We didn't find it
return NULL;
}
像这样使用它:
if (($val = array_select($array, 'Field', 'Field1', 'Question')) !== NULL) {
// Value was found
echo $val;
} else {
// Value not found
echo "Not found!";
}
这与以下 SQL 查询大致相同:
SELECT Question
FROM $array
WHERE Field = 'Field1'
这也支持将'*'
传递给或省略最后一个参数以返回整个对象,这与
SELECT *
FROM $array
WHERE Field = 'Field1'
看到它工作
听起来您想通过提供Field
来获取Question
的值。尝试类似操作:
function getQuestion($field, $array){
// Default to false if value not found
$question = false;
foreach($array as $data){
if($data->Field == $field){
$question = $data->Question;
break;
}
}
return $question;
}
。然后:
if($question = getQuestion('Feild1', $required)){
// Do something with it...
}
有很多方法可以做到这一点,但这种简单的方法应该有效。
干杯
检查整个数据集并利用 PHP 5.3 返回匹配事件。
$arr = array(
0 => (object) array('Field' => 'Field1', 'Question' => 'Question1', 'DataType' => 'Boolean'),
1 => (object) array('Field' => 'Field2', 'Question' => 'Question2', 'DataType' => 'varchar')
);
function get_value($needle, $haystack)
{
return array_filter($haystack, function($item) use ($needle) {
return in_array($needle, get_object_vars($item));
});
}
print_r(get_value('Field1', $arr));
输出:
Array
(
[0] => stdClass Object
(
[Field] => Field1
[Question] => Question1
[DataType] => Boolean
)
)