PHP按值分组数组 [英] PHP Group array by values
问题描述
我有一个像这样的数组:
I have an array like this:
Array (
[0] => ing_1_ing
[1] => ing_1_amount
[2] => ing_1_det
[3] => ing_1_meas
[4] => ing_2_ing
[5] => ing_2_amount
[6] => ing_2_det
[7] => 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
)
)
可能还有许多其他类似的项目:ing_NUMBER_type
There may be many other items named like that: ing_NUMBER_type
如何将第一个数组按所需方式分组?我尝试了此操作,但是由于某些原因,strpos()
有时会失败:
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? Can you advice?
推荐答案
这取决于您要实现的目标,如果要使用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 use sscanf
method in your loop to parse values:
$result = array();
foreach ($firstArray as $value)
{
$n = sscanf($value, 'ing_%d_%s', $id, $string);
if ($n > 1)
{
$result[$id][] = $value;
}
}
这篇关于PHP按值分组数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!