php - 创建数组换行符并将值添加到多维数组中
问题描述
我有一组值作为字符串,如下所示:
MyCustomProductID1
MyCustomProductID2
然后我继续用这些值创建一个数组explode( "\n", $myProductIdString)
现在我有额外的数据(字符串),我想将它们与我的第一个数组中的值结合起来。我想把这个简单的数组变成一个多维数组:
Array
(
[0] => Array
(
[id] => MyCustomProductID1
[url] => http://example.com/MyCustomProductID1.jpg
)
[1] => Array
(
[id] => MyCustomProductID2
[url] => http://example.com/MyCustomProductID2.jpg
)
)
如何将第一个数组转换为多维数组并随之推送数据?
解决方案
而不是直接将值分配给数组使用循环-
<?php
$str = "MyCustomProductID1
MyCustomProductID2";
$arr = explode("\n", $str);
$result = [];
$url_array = ["http://example.com/MyCustomProductID1.jpg", "http://example.com/MyCustomProductID2.jpg"];
for($i=0;$i<count($arr);$i++){
$result[$i]['id'] = $arr[$i];
$result[$i]['url'] = $url_array[$i];
}
print_r($result);
?>
推荐阅读
- java - 从java调用python脚本并逐行收集输出
- c# - 在不使用请求或上下文的情况下获取 ASP.NET MVC 中的绝对基本 url
- css - 无法更改 Telerik 的宽度:RadComboBox
- php - Laravel 会话的唯一数据输入
- java - 如何指定 JDK 的 orbd.exe(对象请求代理守护程序)使用的端口范围?
- python - 使用 Python 编写长 JSON 文档
- python - 使用张量索引对张量进行切片
- javascript - datepicker 禁用期货日期并将今天日期显示为默认日期
- django - Django 自定义组模型
- c# - 没有添加到提交但存在未跟踪的文件