Table of Contents
php索引数组按需处理成关联数组?
Jun 06, 2016 pm 08:24 PM
php
问题可能有些描述的不是很好,我简单举个栗子
<code>//需求 $arr = array('100', '101', '102', '103', '104', '105'); $newArr = array(array('id'=>'100'), array('id'=>'101'), array('id'=>'102'), array('id'=>'103'), array('id'=>'104'), array('id'=>'105')); //我的处理方式是 $newArr = []; foreach($arr as $val) { $newArr[] = array('id'=>$val); } </code>
Copy after login
Copy after login
上述方法可以实现我的需求,还有什么其他方式可以实现?我找到一个内置函数array_chunk($arr, 1, true)
但是,这个键名是设置不了的。
回复内容:
问题可能有些描述的不是很好,我简单举个栗子
<code>//需求 $arr = array('100', '101', '102', '103', '104', '105'); $newArr = array(array('id'=>'100'), array('id'=>'101'), array('id'=>'102'), array('id'=>'103'), array('id'=>'104'), array('id'=>'105')); //我的处理方式是 $newArr = []; foreach($arr as $val) { $newArr[] = array('id'=>$val); } </code>
Copy after login
Copy after login
上述方法可以实现我的需求,还有什么其他方式可以实现?我找到一个内置函数array_chunk($arr, 1, true)
但是,这个键名是设置不了的。
array_map()函数可以实现你的需求:
<code>$arr = array('100', '101', '102', '103', '104', '105'); function make($v) { return array('id'=>$v); } $newArr=array_map('make', $arr); var_dump($newArr); //多谢楼下坛友建议 $newArr=array_map(function ($v){return array('id'=>$v);},$arr);</code>
Copy after login
补充下,上面的写法还可以用匿名函数使其更优雅。
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article
How Long Does It Take To Beat Split Fiction?
3 weeks ago
By DDD
Repo: How To Revive Teammates
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update?
3 weeks ago
By 王林
Two Point Museum: All Exhibits And Where To Find Them
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌

Hot tools Tags

Hot Article
How Long Does It Take To Beat Split Fiction?
3 weeks ago
By DDD
Repo: How To Revive Teammates
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update?
3 weeks ago
By 王林
Two Point Museum: All Exhibits And Where To Find Them
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian

How To Set Up Visual Studio Code (VS Code) for PHP Development
