0

我有一个数组,如下所示。我想回显一个特定的值。现在我正在做的是:

$array[0]->Question

所以,它输出: Question1

但我不想要这个解决方案。

有没有办法在没有键的情况下回显特定值,例如(它不是解决方案):

$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
        )

)
4

3 回答 3

1

听起来您想Question通过提供Field. 尝试类似:

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...
}

有很多方法可以做到这一点,但这种简单的方法应该有效。

干杯

于 2012-05-16T15:28:02.547 回答
1

SELECT这与简单的 SQL查询基本相同。此函数将提供类似的结果:

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'

看到它工作

于 2012-05-16T15:18:27.107 回答
0

利用 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
        )

)
于 2012-05-16T15:50:05.050 回答