Constraint elements in a 2D array to a particular number a particular number of times

I have a 2d array, I want to constraint the elements in a way that the total no of times an element appears can be constrained to a particular value.
For eg: if we have a variable like rand bit [5:0] temp_id [4][4], out of the 16 elements in this 2d array I want an element =8 to appear 4 times, the element can appear 4 times in a row or 4 times in a column, it can appear diagonally, or in any random order.

class problem7;
  rand bit [5:0] temp_id [][];

 constraint size {
  temp_id.size() ==4;
 foreach(temp_id[i]) temp_id[i].size() == 4;
}
// constraint for 8 to appear 4 times in this 2d array.
endclass
module check;
 problem7 p7;
  initial 
  begin
  p7 = new();
  p7.randomize();
 foreach(p7.temp_id[i]) $display("%0p", temp_id[i]);
 end
endmodule.

Try this along with some corrections to your existing code:

class problem7;
  rand bit [5:0] temp_id [][];
 constraint size {
  temp_id.size() ==4;
   foreach(temp_id[i]) temp_id[i].size() == 4;
}
// constraint for 8 to appear 4 times in this 2d array.
  constraint element_count {
    temp_id.sum(D1) with (D1.sum(D2) with (int'(D2 == 8) ) ) == 4;
}
endclass
module check;
  problem7 p7 = new();;
  initial 
  begin
    assert(p7.randomize());
    foreach(p7.temp_id[i]) $display("%0p", p7.temp_id[i]);
 end
endmodule

Thanks Dave, this worked. Can you tell us where can we find details about sum() operators for cases like these? Or something that we can go over, which would be helpful. I went through Chris spears and some part of LRM, could not find something like what we have in the above example. Do u have any blog/link which elaborates use of sum() for different cases.

https://verificationacademy.com/forums/search?q=sum%20constraint%202d