【问题标题】:PHP, array of objects, how can I use one set of object values as the array keysPHP,对象数组,如何使用一组对象值作为数组键
【发布时间】:2018-12-01 06:02:40
【问题描述】:

我有一个如下所示的数组:

array:9 [▼
  0 => {#279 ▼
    +"id": "103"
    +"name": "In what city did you meet your spouse/partner?"
  }
  1 => {#280 ▼
    +"id": "100"
    +"name": "What is the first name of the person you first kissed?"
  }
  2 => {#281 ▼
    +"id": "102"
    +"name": "What is the name of your favorite childhood friend?"
  }
  3 => {#282 ▶}
  4 => {#283 ▶}
  5 => {#284 ▶}
  6 => {#285 ▶}
  7 => {#286 ▶}
  8 => {#287 ▶}
]

这是 dd()。我想知道如何将其转换为键/值数组,使用 id 作为键和名称作为值。像这样的:

array(
  '103' => 'In what city did you meet your spouse/partner?',
  '100' => 'What is the first name of the person you first kissed?'
);

【问题讨论】:

    标签: php arrays laravel


    【解决方案1】:

    从 PHP 7 开始,您可以在对象上使用array_column(),第三个参数作为要索引的列...

    $questions = array_column($data, "name", "id");
    

    【讨论】:

      【解决方案2】:

      您可以使用collections pluck method

      $collection = collect($array)->pluck("name","id");
      

      如果你想得到一个数组回来使用:

      $collection->all();
      

      【讨论】:

        【解决方案3】:

        我想通了:

        $data = DB::connection()->select($sql);
        
        $questions = [];
        
        foreach ($data as $question) {
            $questions[$question->id] = $question->name;
        }
        

        对任何更巧妙的解决方案开放,但这绝对有效!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-01-14
          • 2018-06-15
          • 1970-01-01
          • 1970-01-01
          • 2021-02-14
          • 1970-01-01
          • 2019-04-26
          • 2020-04-13
          相关资源
          最近更新 更多