[英]create arrays from elements of another array
I have a array called array3; 我有一个名为array3的数组;
Array
(
[0] => Commercial
[1] => Infrastructure
)
I want to iterate thtough each element of this array and create individual arrays based on the values. 我想遍历此数组的每个元素,并根据值创建单个数组。 I have tried this; 我已经尝试过了
$array4 = array();
$array5= array();
foreach ($array3 as $value) {
$array4[] = array('v' => count(search($rows, 'domaindesc', $value)));
$array4[] = array('v' => $value);
$array5[] = array('c' => $array4);
}
the search function is returning the no of maching elements from another array. 搜索功能正在从另一个数组中返回所有的处理元素。 The output I get from the above code is 我从上面的代码中得到的输出是
Array
(
[0] => Array
(
[c] => Array
(
[0] => Array
(
[v] => 5
)
[1] => Array
(
[v] => Commercial
)
)
)
[1] => Array
(
[c] => Array
(
[0] => Array
(
[v] => 5
)
[1] => Array
(
[v] => Commercial
)
[2] => Array
(
[v] => 1
)
[3] => Array
(
[v] => Infrastructure
)
)
)
)
What I am trying to get is; 我想要得到的是;
Array
(
[0] => Array
(
[c] => Array
(
[0] => Array
(
[v] => 5
)
[1] => Array
(
[v] => Commercial
)
)
)
[1] => Array
(
[c] => Array
(
[0] => Array
(
[v] => 1
)
[1] => Array
(
[v] => Infrastructure
)
)
)
)
Any help is appreciated 任何帮助表示赞赏
Each iteration, you are adding onto $array4 and putting that into $array5 每次迭代,您将添加到$ array4并将其放入$ array5
Try re-declaring $array4 each iteration: 尝试在每次迭代中重新声明$ array4:
$array5 = array();
foreach ($array3 as $value) {
$array4 = array();
$array4[] = array('v' => count(search($rows, 'domaindesc', $value)));
$array4[] = array('v' => $value);
$array5[] = array('c' => $array4);
}
EDIT: For style, I would personally have written it as such: 编辑:对于样式,我个人会这样写:
$array5 = array();
foreach ($array3 as $value) {
$array5[] = array('c' => array(
array('v' => count(search($rows, 'domaindesc', $value))),
array('v' => $value),
));
}
Note the trailing comma in the array declaration is intentional, making it easier for other devs to add more items to the declaration if needed. 请注意,数组声明中的尾部逗号是有意为之,从而使其他开发人员更容易在需要时向声明添加更多项。 PHP allows this and I take advantage of it. PHP允许这样做,我利用了它。
EDIT2: If you are not concerned about your PHP code not working on versions of PHP prior to 5.4, I prefer to use square brackets to declare an array instead of array(). EDIT2:如果您不担心PHP代码无法在5.4之前的PHP版本上使用,我更喜欢使用方括号来声明一个数组而不是array()。 It ends up looking even cleaner: 最终看起来更加干净:
$array5 = [];
foreach ($array3 as $value) {
$array5[] = ['c' => [
['v' => count(search($rows, 'domaindesc', $value))],
['v' => $value],
]];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.