按值前缀对平面数组进行分组并填充索引数组的索引数组
我有一个像这样的数组:
[
'ing_1_ing',
'ing_1_amount',
'ing_1_det',
'ing_1_meas',
'ing_2_ing',
'ing_2_amount',
'ing_2_det',
'ing_2_meas',
]
我想将这些值分组到一个这样的数组中:
Array (
[0] => Array(
[0] => ing_1_ing
[1] => ing_1_amount
[2] => ing_1_det
[3] => ing_1_meas
)
[1] => Array(
[0] => ing_2_ing
[1] => ing_2_amount
[2] => ing_2_det
[3] => ing_2_meas
)
)
可能还有许多其他这样命名的项目: ing_NUMBER_type
如何按照我想要的方式将第一个数组分组它?我尝试过这个,但由于某种原因,strpos()
有时会失败:
$i = 1;
foreach ($firstArray as $t) {
if (strpos($t, (string)$i)) {
$secondArray[--$i][] = $t;
} else {
$i++;
}
}
出了什么问题?
I have an array like this:
[
'ing_1_ing',
'ing_1_amount',
'ing_1_det',
'ing_1_meas',
'ing_2_ing',
'ing_2_amount',
'ing_2_det',
'ing_2_meas',
]
And I want to group the values into an array like this:
Array (
[0] => Array(
[0] => ing_1_ing
[1] => ing_1_amount
[2] => ing_1_det
[3] => ing_1_meas
)
[1] => Array(
[0] => ing_2_ing
[1] => ing_2_amount
[2] => ing_2_det
[3] => ing_2_meas
)
)
There may be many other items named like that: ing_NUMBER_type
How do I group the first array to the way I want it? I tried this, but for some reason, strpos()
sometimes fails:
$i = 1;
foreach ($firstArray as $t) {
if (strpos($t, (string)$i)) {
$secondArray[--$i][] = $t;
} else {
$i++;
}
}
What is wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这取决于您想要实现的目标,如果您想按块分割数组,请使用 array_chunk 方法,如果您尝试基于数字创建多维数组,您可以使用 sscanf循环中的方法来解析值:
It depends what you are trying to achieve, if you want to split array by chunks use
array_chunk
method and if you are trying to create multidimensional array based on number you can usesscanf
method in your loop to parse values:这将创建:
This creates:
我要做的事情是这样的:
基本上,您迭代第一个数组,查看其中有什么数字,然后将其放在最终数组中的正确位置。
编辑。如果您知道数字始终从
1
开始,则可以将$number = $matches[1];
替换为$number = $matches[ 1] - 1;
,这样您将得到与您发布的示例完全相同的结果。What I'd do is something like this:
Basically you iterate through your first array, see what number is there, and put it in the right location in your final array.
EDIT. If you know you'll always have the numbers start from
1
, you can replace$number = $matches[1];
for$number = $matches[1] - 1;
, this way you'll get exactly the same result you posted as your example.每次遇到新组时,将新组引用推送到结果数组中。这样,您可以简单地将元素推入引用中,而无需查找或跟踪每个组的索引。 演示
输出:
Push a new group reference into the result array each time a new group is encountered. This way you can simply push elements into the reference instead of needing to find or keep track of the index of each group. Demo
Output: