Reputation: 93
I have array with 45 elements. I need to make from it multidimensiona array. This is how it looks like:
Array45: [
0 => {
+'MODEL': "AAA"
+'PRICE': 12.00
+'SUBMODEL_NAME': "abc"
}
1 => {
+'MODEL': "AAA"
+'PRICE': 12.00
+'SUBMODEL_NAME': ""
}
2 => {
+'MODEL': "BBB"
+'PRICE': 12.00
+'SUBMODEL_NAME': "bcd"
}
3 => {
+'MODEL': "AAA"
+'PRICE': 12.00
+'SUBMODEL_NAME': ""
}
]
And now: If record doesn't have 'SUBMODEL_NAME' I need to put it in one array with previous record which has 'SUBMODEL_NAME'. And in this case it should look like:
Array: [
0 => [
0 => {
+'MODEL': "AAA"
+'PRICE': 12.00
+'SUBMODEL_NAME': "abc"
}
1 => {
+'MODEL': "AAA"
+'PRICE': 12.00
+'SUBMODEL_NAME': ""
}
1 => [
0 => {
+'MODEL': "BBB"
+'PRICE': 12.00
+'SUBMODEL_NAME': "bcd"
}
1 => {
+'MODEL': "AAA"
+'PRICE': 12.00
+'SUBMODEL_NAME': ""
}
]
etc.
I'm in foreach loop where I try to put every next record without SUBMODEL_NAME to previous but I get stuck. It's something like this:
$j = -1;
$newArray = [];
foreach($items as $item){
if ($index->SUBMODEL_NAME) {
$j++;
$newArray [$j][] = $index ;
}
}
EDIT Thank you all for help! I've implement soulution proposed by @user1309690 and it looks like it works perfectly. Thank for you'r help and time
Upvotes: 4
Views: 864
Reputation: 38502
Another way to do it-
$result = [];
foreach($array as $k=>$v){
$i=0;
if($v['SUBMODEL_NAME']==''){
$i++;
$k = $k-1;
}
$result[$k][$i]= $v;
}
$result = array_values($result);
print_r($result);
DEMO: https://3v4l.org/3aTgR
Upvotes: 1
Reputation: 3476
Try this.
$j = -1;
$newArray = [];
foreach($items as $item){
if ($item['SUBMODEL_NAME']) {
$j++;
}
$newArray [$j][] = $item ;
}
Upvotes: 3