我想知道是否有人可以为我解释一些事情。
我在Laravel中使用以下代码创建一个数组。
如何将$ graphs数组添加到循环中的每个$ website_array?
$website_array = [];
foreach ($websites as $website) {
array_push($website_array, $website);
$graphs = [
'thisdata' => 'This data',
'newdata' => 'New data',
];
}
我最终想要的是以下内容
website
website data
website data
website data
graphs
thisdata
newdata
website
website data
website data
website data
graphs
thisdata
newdata
答案 0 :(得分:0)
您可能想尝试下面的内容,您也可以Quick-Test Here:
<?php
$website_array = [];
$websites = [
"http://www.domain-1.com/a",
"http://www.domain-2.com/b",
"http://www.domain-3.com/c",
"http://www.domain-4.com/d",
"http://www.domain-5.com/e",
"http://www.domain-6.com/f",
"http://www.domain-7.com/g",
];
foreach ($websites as $website) {
$graphs = [
'thisdata' => 'This data',
'newdata' => 'New data',
];
$data = [
'website' => $website,
'graphs' => $graphs,
];
$website_array[] = $data;
}
var_dump($website_array);
// PRODUCES:
array (size=7)
0 =>
array (size=2)
'website' => string 'http://www.domain-1.com/a' (length=25)
'graphs' =>
array (size=2)
'thisdata' => string 'This data' (length=9)
'newdata' => string 'New data' (length=8)
1 =>
array (size=2)
'website' => string 'http://www.domain-2.com/b' (length=25)
'graphs' =>
array (size=2)
'thisdata' => string 'This data' (length=9)
'newdata' => string 'New data' (length=8)
2 =>
array (size=2)
'website' => string 'http://www.domain-3.com/c' (length=25)
'graphs' =>
array (size=2)
'thisdata' => string 'This data' (length=9)
'newdata' => string 'New data' (length=8)
3 =>
array (size=2)
'website' => string 'http://www.domain-4.com/d' (length=25)
'graphs' =>
array (size=2)
'thisdata' => string 'This data' (length=9)
'newdata' => string 'New data' (length=8)
4 =>
array (size=2)
'website' => string 'http://www.domain-5.com/e' (length=25)
'graphs' =>
array (size=2)
'thisdata' => string 'This data' (length=9)
'newdata' => string 'New data' (length=8)
5 =>
array (size=2)
'website' => string 'http://www.domain-6.com/f' (length=25)
'graphs' =>
array (size=2)
'thisdata' => string 'This data' (length=9)
'newdata' => string 'New data' (length=8)
6 =>
array (size=2)
'website' => string 'http://www.domain-7.com/g' (length=25)
'graphs' =>
array (size=2)
'thisdata' => string 'This data' (length=9)
'newdata' => string 'New data' (length=8)
答案 1 :(得分:0)
首先创建课程&#39; ClassWebsite&#39;
class ClassWebsite
{
public $website;
public $graphs;
}
并使用它
$website_array = [];
$i = 0;
foreach ($websites as $website) {
$obj_class = new ClassWebsite();
$obj_class->website = $website;
$graphs = [
'thisdata' => 'This data',
'newdata' => 'New data',
];
$obj_class->graphs = $graphs;
$website_array[$i] = $obj_class;
$i++;
}