php - Add one more element to array in loop with PHP
问题描述
I have array like below:
$arr=[["id"=>"001","name"=>"Hello","pict"=>"hello.jpg"],["id"=>"002","name"=>"Abc","pict"=>"abc.jpg"]];
i want to add one more element to array $arr by "link"=>"uploads/hello.jpg" My expected result:
$arr=[["id"=>"001","name"=>"Hello","pict"=>"hello.jpg","link"=>"uploads/hello.jpg"],["id"=>"002","name"=>"Abc","pict"=>"abc.jpg","link"=>"uploads/abc.jpg"]];
Any solution for this thank.
解决方案
You can iterate over the array using foreach
, passing a reference into the loop to allow the values to be modified directly:
$arr=[["id"=>"001","name"=>"Hello","pict"=>"hello.jpg"],["id"=>"002","name"=>"Abc","pict"=>"abc.jpg"]];
foreach ($arr as &$a) {
$a['link'] = 'uploads/' . $a['pict'];
}
print_r($arr);
Output:
Array
(
[0] => Array
(
[id] => 001
[name] => Hello
[pict] => hello.jpg
[link] => uploads/hello.jpg
)
[1] => Array
(
[id] => 002
[name] => Abc
[pict] => abc.jpg
[link] => uploads/abc.jpg
)
)
推荐阅读
- stm32 - CANBUS 波特率配置含义
- spring - Spring Cloud 数据流 Git 源码
- ios - 我可以在 Xcode 上为横向和纵向方向创建多个启动画面吗?
- c# - Canvas.Left 属性以哪个单位测量?
- asp.net - 如何在模态弹出窗口中清除 iframe 标签的多个 youtube url?
- scala - 动态合并 Akka 流
- google-apps-script - 使用应用程序脚本将电子表格表格嵌入谷歌文档
- node.js - 以通用方式解析简单值类型
- jquery - 无法从 AJAX 编辑现有记录时填充两列多选
- angular-cli - 使用 ng --version 命令时出现错误而不是 Angular 的版本