简体   繁体   中英

Create multidimensional array in foreach loop

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

Try this.

$j = -1;
$newArray = [];
foreach($items as $item){
    if ($item['SUBMODEL_NAME']) {
        $j++;
    }
    $newArray [$j][] = $item ;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM