我想用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语句,但它重复了结果,因为我不知道如何实现它。
答案 0 :(得分:1)
在这里,试试这个(clearInterval
):
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"
}
}
答案 1 :(得分:1)
使用您提供的确切代码作为示例:
修改:已更新,因为您更新了问题
$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"
}
}
答案 2 :(得分:1)
如果两个数组的长度相同,并且单维($codes[] =[...]
应该读取$coded = [...]
),那么您可以创建一个单独的循环,并将值推送到一个新数组中,然后使用{{ 1}}获取所需的json输出:
json_encode
如果你的$out=[];
foreach($urls as $key=>$url)
$out[]=['url'=>$url, 'code'=>$codes[$key]];
echo json_encode($out);
数组是有意的多维数组,那么你需要在其中访问正确的内部数组,例如:
$codes
答案 3 :(得分:1)
// 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);
注意:如果两个阵列可能没有相同的长度,请添加一些额外的控件。