我有一个嵌套数组,我希望根据原始值中的值处理另一个嵌套数组。
这是我的原始数组,它是嵌套的,因为我稍后会引入其他值。
$dataArray = array (
0 => array(
"adgroupid" => "5426058726"
),
1 => array(
"adgroupid" => "5426058086"
),
2 => array(
"adgroupid" => "5426058086"
),
3 => array(
"adgroupid" => "5426058087"
),
4 => array(
"adgroupid" => "5426058087"
),
5 => array(
"adgroupid" => "5426058088"
),
6 => array(
"adgroupid" => "5426058089"
),
7 => array(
"adgroupid" => "5426058089"
),
8 => array(
"adgroupid" => "5426058090"
这是我目前得到的结果,请注意数组1和1中的字符串。 2应该嵌套在同一个数组中,如3& 5
array (size=10)
0 =>
array (size=1)
0 => string '5426058726' (length=10)
1 =>
array (size=1)
0 => string '5426058086' (length=10)
2 =>
array (size=1)
0 => string '5426058086' (length=10)
3 =>
array (size=2)
0 => string '5426058087' (length=10)
1 => string '5426058087' (length=10)
4 =>
array (size=1)
0 => string '5426058088' (length=10)
5 =>
array (size=2)
0 => string '5426058089' (length=10)
1 => string '5426058089' (length=10)
6 =>
array (size=4)
0 => string '5426058090' (length=10)
这是我的代码,我需要使用if语句,因为在稍后阶段我想引入另一个参数:
$newdataArray = array();
$j = 0; // Set value of working variables
$adgroupidcheck = 0;
foreach ($dataArray as $value) { // Loop through the array
if( $adgroupidcheck != $value['adgroupid'] ) { // Check $adgroupidcheck
$newdataArray[][] = $value['adgroupid']; // Create a new nested array
$j ++; // increment $j
} else {
$newdataArray[$j][] = $value['adgroupid']; // Add to the current array
}
$adgroupidcheck = $value['adgroupid']; // Set $adgroupidcheck
}
所以我的问题是我的代码只在数组检查循环的第一个实例没有工作后才能工作。
任何帮助都将不胜感激。
谢谢。
答案 0 :(得分:0)
您应该预先增加$j
值,以便将其添加为正确的数组。否则它会被发送到下一个,只需快速跟踪。
if( $adgroupidcheck != $value['adgroupid'] ) {
$newdataArray[++$j][] = $value['adgroupid'];
} else {
$newdataArray[$j][] = $value['adgroupid'];
}
答案 1 :(得分:0)
foreach ($dataArray as $value) {
if( $adgroupidcheck != $value['adgroupid'] ) {
$newdataArray[][] = $value['adgroupid'];
$j ++; // increment $j
} else {
$j--; //decrease j which was incremented after inserting one value
$newdataArray[$j][] = $value['adgroupid'];
$j++; // increment it again for it's original or new index
}
$adgroupidcheck = $value['adgroupid'];
}