PHP,对象数组,如何使用一组对象值作为数组键

时间:2018-06-21 19:43:45

标签: php arrays laravel

我有一个看起来像这样的数组:

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?'
);

3 个答案:

答案 0 :(得分:8)

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

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

答案 1 :(得分:1)

您可以使用collections pluck method

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

如果您想找回阵列,请使用:

$collection->all();

答案 2 :(得分:0)

我想出了:

$data = DB::connection()->select($sql);

$questions = [];

foreach ($data as $question) {
    $questions[$question->id] = $question->name;
}

欢迎使用任何更精简的解决方案,但这绝对有效!