1

I have an array that groups different items by item type. I am grouping the result by category_id field. What I want is the output to be

item1 = 3
item2 = 2

My array looks like this if I do a var_dump()

array(2) {
  ["item1"]=>
   array(3) {
    [0]=>
    string(1) "3"
    [2]=>
    string(1) "5"
    [4]=>
    string(1) "7"
  }
  ["item2"]=>
  array(2) {
    [1]=>
    string(1) "4"
    [3]=>
    string(1) "6"
  }
}

Here is the code I am using:

            $items = Item::where('order_id','=',$payload["orderId"])->get();
            $itemsGrouped = [];
            $count = 0;
            foreach($items as $item){
                $itemsGrouped[$item->category_id][$count] = $item->id;
                $count++;
            }

           foreach($itemsGrouped as $grp){
               echo key($itemsGrouped).'='.count($grp).'<br>';
           };

And here is what I am currently getting. The count is working but not the $itemsGrouped key. It is duplicated.

item2=3<br>item2=2<br> 
0

3 Answers 3

2

Change your code as below

foreach($itemsGrouped as $key => $grp){
     echo $key.'='.count($grp).'<br>';
};

In order to use key() function, you need to traverse the array using next/current function

Sign up to request clarification or add additional context in comments.

Comments

1
       foreach($itemsGrouped as $key => $grp){
           echo $key.'='.count($grp).'<br>';
       };

key() function returns the current element's key, which is defined by an array's internal pointer. Obviously it always points to the last element.

Comments

0
 $myarray = "Your array";

    $count = array();  // create an empty array

    foreach($myarray as $arr) {  
        foreach($arr as $a) {  
            $key = array_keys($a); 
            $count[$key[0]]++;
        }
    }

    print_r($count);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.