没有Loop的数组的回声值

时间:2012-05-16 15:12:38

标签: php arrays

我有一个类似下面显示的示例的数组。 我想回应一个具体的价值。现在我正在做的是:

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

)

3 个答案:

答案 0 :(得分:1)

这与简单的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'

See it working

答案 1 :(得分: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...
}

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

干杯

答案 2 :(得分: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
        )

)
相关问题