skip to Main Content

I wanna know how to iterate an array to count elements in PHP, I’ve trying next,

foreach ($items as $item) {
                $tm[$item->provider->name] = [];
                foreach ($items as $item) {
                    $tm[$item->provider->name][$item->product->brand->name] = isset($tm[$item->provider->name][$item->product->brand->name]) ? $tm[$item->provider->name][$item->product->brand->name] + 1 : $tm[$item->provider->name][$item->product->brand->name] = 1;
                }
            }

But I get a wrong result, I get an array but I get a very high number count as if iterated many timesmany times

The structure of the array is as follows

[{
    "id": 1,
    "product": {
        "id": 1,
        "brand": {
            "id": 1,
            "name": "iphone"
        }
    },
    "provider": {
        "id": 1,
        "name": "at&t"
    }
},
{
    "id": 2,
    "product": {
        "id": 2,
        "brand": {
            "id": 2,
            "name": "iphone"
        }
    },
    "provider": {
        "id": 1,
        "name": "at&t"
    }
},
{
    "id": 3,
    "product": {
        "id": 3,
        "brand": {
            "id": 3,
            "name": "iphone"
        }
    },
    "provider": {
        "id": 1,
        "name": "t-mobile"
    }
}]

2

Answers


  1. From your code example you apparently want to count how many occurrences are for each "thing" in your array, otherwise count() would have probably sufficed…

    Though you are doing a lot of work to pre-init the counting array – that is completely unneeded: read about auto-vivifcation.

    Code like so would probably suffice (I’m not following your example code here – you’d need to work out to your needs):

    $counters = [];
    foreach ($items as $item)
      @$counters[$item->name][$item->model]++;
    
    Login or Signup to reply.
  2. IIUC, you are trying to count the product->brand->name values for each provider->name. You can do that using this code:

    $tm = array();
    foreach ($items as $item) {
        $product = $item->product->brand->name;
        $provider = $item->provider->name;
        $tm[$provider][$product] = ($tm[$provider][$product] ?? 0) + 1;
    }
    
    print_r($tm);
    

    Output (for your sample data):

    Array
    (
        [at&t] => Array
            (
                [iphone] => 2
            )
        [t-mobile] => Array
            (
                [iphone] => 1
            )
    )
    

    Demo on 3v4l.org

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search