简体   繁体   English

PHP:将对象转换为以对象属性为键的关联数组

[英]PHP: Convert Object to Associative Array with Object Property as Key

In PHP, I'd like to convert an array of objects like the following to a PHP array, using one of the properties as the associative array keys.在 PHP 中,我想将如下所示的对象数组转换为 PHP 数组,使用其中一个属性作为关联数组键。

[
  { "id": 2, "name": "Suzy" },
  { "id": 3, "name": "Joe" },
  { "id": 4, "name": "Sara" }
]

like this...像这样...

[
  2 => "Suzy",
  3 => "Joe",
  4 => "Sara"
]

I can't use array_map because you can't set the keys from my understanding, but I'm wondering if there's a one-liner way to do it without a foreach loop.我不能使用 array_map 因为你不能根据我的理解设置键,但我想知道是否有一种没有 foreach 循环的单行方式来做到这一点。

To be clear, I want to maintain the keys in the output array, not puts the original keys inside the new array values like they do here: PHP's array_map including keys需要明确的是,我想维护输出数组中的键,而不是像这里那样将原始键放入新数组值中: PHP 的 array_map 包括键

It appears by "object" you mean a JSON object.它出现在“对象”中,你的意思是一个 JSON 对象。 Given that, you can use array_column() to pull out a single column from each row, and then array_combine() to use one column for the keys and another for the values:鉴于此,您可以使用array_column()从每一行中提取一列,然后使用array_combine()将一列用于键,另一列用于值:

$json = '[
    { "id": 2, "name": "Suzy" },
    { "id": 3, "name": "Joe" },
    { "id": 4, "name": "Sara" }
]';
$array = json_decode($json, true);
$out = array_combine(array_column($array, 'id'), array_column($array, 'name'));
print_r($out);

Yields:产量:

Array
(
    [2] => Suzy
    [3] => Joe
    [4] => Sara
)

2 liners and has a foreach though. 2 衬垫,但有一个 foreach。

<?php

$json = '[
  { "id": 2, "name": "Suzy" },
  { "id": 3, "name": "Joe" },
  { "id": 4, "name": "Sara" }
]';

$new_array = [];
foreach(json_decode($json,true) as $each_object) $new_array[$each_object['id']] = $each_object['name'];

print_r($new_array);
$json = '[
    { "id": 2, "name": "Suzy" },
    { "id": 3, "name": "Joe" },
    { "id": 4, "name": "Sara" }
]';
$array = json_decode($json, true);
$result = array_column($array, 'name', 'id');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM