开发者

PHP array issue

开发者 https://www.devze.com 2023-02-02 18:02 出处:网络
I have an Array List that I want to output like m开发者_如何学Pythony example below. How can I achieve it in PHP?

I have an Array List that I want to output like m开发者_如何学Pythony example below. How can I achieve it in PHP?

Array List:
array(
  [0] => First,
  [1] => Second,
  [2] => Third,
)

Want to output like this:
array(
  [First] => First,
  [Second] => Second,
  [Third] => Third
)

Thanks, steamboy


You can use array_combine() and pass two copies of your original array:

$new_list = array_combine($list, $list);
print_r($new_list);

Maps the contents of the first argument as keys and the contents of the second argument as values, in their defined order.


I haven't tested it, but this should work

foreach ($array as $key => $value) {
    $array[$value] = $value;
    unset($array[$key]);
}

That should do it


That is redundancy at its finest. It makes little sense to have keys matching their values, and probably highlights the need for a design change, or a potential optimisation somewhere in your application. Turning this:

array(
  [0] => First,
  [1] => Second,
  [2] => Third,
)

into this:

array(
  [First] => First,
  [Second] => Second,
  [Third] => Third
)

effectively reduces the amount of information you are storing, since you the developer know in advance that keys should match values.

0

精彩评论

暂无评论...
验证码 换一张
取 消