我想用PHP实现这种数组。
[
{
"url": "https://url1.com",
"code": "BNXl421s"
},
{
"url": "https://url2.com",
"code": "BNKpt1L2"
},
{
"url": "https://url3.com",
"code": "BMwhPRih"
}
]
虽然我有这些数组:
$urls =
[
"https://url1.com",
"https://url2.com",
"https://url3.com"
]
$codes=
[
"BNXl421s",
"BNKpt1L2",
"BMwhPRih"
]
我尝试编写 2 个 foreach 语句,但它会重复结果,因为我不知道如何实现这一点。
在这里,试试这个(或者这里的演示):
function merge($array1,$array2){
$output = [];
for($i = 0; $i < count($array1); $i++){
$output[$array1[$i]] = $array2[$i];
}
return $output;
}
var_dump(merge($urls,$codes));
这将输出一个像这样的数组
Array(
"https://url1.com" => "BNXl421s",
"https://url2.com" => "BNKpt1L2",
"https://url3.com" => "BMwhPRih"
)
function merge($array1,$array2){
$output = [];
for($i = 0; $i < count($array1); $i++){
$output[] = array("url" => $array1[$i], "code" => $array2[$i]);
}
return $output;
}
var_dump(merge($urls,$codes));
同样的想法,但是这个输出:
array(3) {
[0]=>
array(2) {
["url"]=>
string(16) "https://url1.com"
["code"]=>
string(8) "BNXl421s"
}
[1]=>
array(2) {
["url"]=>
string(16) "https://url2.com"
["code"]=>
string(8) "BNKpt1L2"
}
[2]=>
array(2) {
["url"]=>
string(16) "https://url3.com"
["code"]=>
string(8) "BMwhPRih"
}
}
尝试一下这里
假设两个数组的长度相同,并且是单维的(
$codes[] =[...]
应读取$coded = [...]
),那么您可以创建一个循环,并将值推送到新数组中,然后使用json_encode
获取所需的json输出:
$out=[];
foreach($urls as $key=>$url)
$out[]=['url'=>$url, 'code'=>$codes[$key]];
echo json_encode($out);
如果您的
$codes
数组是内涵多维的,那么您需要访问 in 中正确的内部数组,例如:
$out[]=['url'=>$url, 'code'=>$codes[0][$key]];
// Your array definitions
$urls =
[
"https://url1.com",
"https://url2.com",
"https://url3.com"
];
// Warning! You had $codes[] here!!! Array of arrays? Not necessary I think...
$codes =
[
"BNXl421s",
"BNKpt1L2",
"BMwhPRih"
];
$results = array();
$obj = new stdClass();
foreach ($urls as $key => $url)
{
$obj->url = $url;
$obj->code = $codes[$key];
$results[]=$obj;
}
// Done! You can check it doing:
var_dump($results);
注意:如果两个数组的长度可能不同,请添加一些额外的控件。
使用您提供的确切代码作为示例:
编辑:已更新,因为您更新了问题
$result = [];
for ($i = 0; $i < 3; $i++) {
$result[$i] = ['url:' => $urls[$i], 'code:' => $codes[$i]];
}
var_dump($result);
输出:
array(3) {
[0]=>
array(2) {
["url:"]=>
string(16) "https://url1.com"
["code:"]=>
string(8) "BNXl421s"
}
[1]=>
array(2) {
["url:"]=>
string(16) "https://url2.com"
["code:"]=>
string(8) "BNKpt1L2"
}
[2]=>
array(2) {
["url:"]=>
string(16) "https://url3.com"
["code:"]=>
string(8) "BMwhPRih"
}
}