【问题标题】:Extract complete array from std class multi dimensional array php从std类多维数组php中提取完整数组
【发布时间】:2016-08-02 10:55:27
【问题描述】:

我正在开发一个考试系统,但在获得正确结果时遇到了问题。 我希望从与问题 ID 466 匹配的答案数组中获得此结果

(
[id] => 234
[firstChoice] => 2
[choice] => 2
[marked] => 
[strikethrough] => Array()
[highlights] => 
[guessed] => 
[difficulty] => easy
[numTimesChanged] => 
[timeElapsed] => 36
)

我有这种类型的答案标准类数组。 我也有相同类型的问题数组。

Array(
[0] => stdClass Object
    (
        [id] => 234
        [firstChoice] => 2
        [choice] => 2
        [marked] => 
        [strikethrough] => Array
            (
            )

        [highlights] => 
        [guessed] => 
        [difficulty] => easy
        [numTimesChanged] => 
        [timeElapsed] => 36
    )

[1] => stdClass Object
    (
        [id] => 466
        [firstChoice] => 3
        [choice] => 3
        [marked] => 
        [strikethrough] => Array
            (
            )

        [highlights] => 
        [guessed] => 
        [difficulty] => easy
        [numTimesChanged] => 
        [timeElapsed] => 5
    )
)

【问题讨论】:

  • 尝试过什么
  • 如果可能的话,我建议在数据生成时将 id 设置为键。

标签: php multidimensional-array stdclass


【解决方案1】:

试试这个:

$result = null;
foreach($array as $value){
    if($value->id == 466){
        $result = $value;
        break;
    }
}

【讨论】:

    【解决方案2】:

    如果你的ID不唯一,可以使用array_filter()

    解决方案:

    <?php
    
    $array = json_decode('[{"id":4,"data":"data1"},{"id":14,"data":"data41"},{"id":14,"data":"data14"}]');
    
    $idSearched = 14;
    
    function filter($item){
        global $idSearched;
        return $item->id === $idSearched;
    }
    
    $res = array_filter($array, "filter");
    print_r($res);
    

    Live example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-29
      • 2020-06-11
      相关资源
      最近更新 更多