Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to get only 3 results when calling a value within a multidimensional array meta with php?

I am working on a comment system and I want to show only 3 results, then I will load the rest on the other side but here I can’t think of how to get only 3.

The values come from a form and I save them in a post goal creating an array.

I show how I get the comments:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel


$datacomments = array_reverse(get_post_meta($product_id, 'propina5', false)); 

foreach ($datacomments as $infocalif){

$comment = $infocalif['comment'];

echo $comment;
}

The array:

echo print_r($datacomments);

Array ( [0] => Array ( [date] => 01-12-2021 01:37 [id] => 2 [rating] => 4 [comment] => bla bla bla [perce] => 0 ) 
[1] => Array ( [date] => 01-12-2021 01:37 [id] => 2 [rating] => 4 [comment] => bla bla bla [perce] => 0 ) 
[2] => Array ( [date] => 01-12-2021 01:37 [id] => 2 [rating] => 4 [comment] => bla bla bla [perce] => 0 ) 
[3] => Array ( [date] => 01-12-2021 01:37 [id] => 2 [rating] => 4 [comment] => bla bla bla [perce] => 0 ) 
[4] => Array ( [date] => 01-12-2021 01:37 [id] => 2 [rating] => 4 [comment] => bla bla bla [perce] => 0 ) ) 1

By default this is how I get all the comments saved in the meta, but I only want to get 3, it will be the last 3 due to array_reverse.

Then I will load everything in a different template so as not to delay the initial load

Any suggestion?

>Solution :

use counter

$cnt = 2;
foreach ($datacomments as $infocalif){

$comment = $infocalif['comment'];

echo $comment;
if (!$cnt--) break;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading