Creating a nested array based on a value
I have a nested array that I want to process into another nested array based on the value in the original.
Here's my original array, it is nested because I will be entering other values ββlater.
$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"
Here's the result I am currently getting, note that the rows in arrays 1 and 2 must be nested in the same array, for example 3 and 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)
Here is my code, I need to use an if statement because at a later stage I want to introduce a different argument:
$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
}
So my problem is that my code only works after the first instance of the array check loop has failed.
Any help would be appreciated.
Thank.
source to share
You should just pre-increment the value $j
so that it is added as a correct array. Otherwise it will be sent to the next one, just do a quick trace.
if( $adgroupidcheck != $value['adgroupid'] ) {
$newdataArray[++$j][] = $value['adgroupid'];
} else {
$newdataArray[$j][] = $value['adgroupid'];
}
source to share
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 original or new index
}
$adgroupidcheck = $value['adgroupid'];
}
source to share