首页 > 解决方案 > 创建数组换行符并将值添加到多维数组中

问题描述

我有一组值作为字符串,如下所示:

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
        )

)

如何将第一个数组转换为多维数组并随之推送数据?

标签: phparrays

解决方案


而不是直接将值分配给数组使用循环-

<?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);
?>

推荐阅读