Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - foreach overlapping issue

Tags:

php

I have API that returns like below:

$arrays = array(
   "1" => array(
       "name" => "Mike",
       "date" => "1/2/2016",
       "criterion" => array(
            "1" => array(
                    "label"  => "Value for Money",
                    "scores" => "5"
                ),
            "2" => array(
                    "label" => "Policy Features And Benefits",
                    "scores" => "1.5"
                ),
            "3" => array(
                    "label" => "Customer Service",
                    "scores" => "3"
                )

        )
   ),
   "2" => array(
       "name" => "Megu",
       "date" => "1/2/2015",
       "criterion" => array(
            "1" => array(
                    "label"  => "Value for Money",
                    "scores" => "2"
                ),
            "2" => array(
                    "label" => "Policy Features And Benefits",
                    "scores" => "3.5"
                ),
            "3" => array(
                    "label" => "Customer Service",
                    "scores" => "1"
                )

        )
   )
);

And PHP code:

$output = '';
$output_criterion = '';

foreach($arrays as $a){

    $criterions_arr = $a['criterion'];
    foreach($criterions_arr as $c){
        $output_criterion .= $c['label'] . ' - ' . $c['scores'] . '<br/>';
    }

    $output .= $a['name'] . '<br/>' . $output_criterion . '<br/>';

}

echo $output; 

Result:

Mike
Value for Money - 5
Policy Features And Benefits - 1.5
Customer Service - 3

Megu
Value for Money - 5
Policy Features And Benefits - 1.5
Customer Service - 3
Value for Money - 2
Policy Features And Benefits - 3.5
Customer Service - 1

However I would like the result to be like below without overlapping in the nested foreach loop:

Mike
Value for Money - 5
Policy Features And Benefits - 1.5
Customer Service - 3

Megu
Value for Money - 2
Policy Features And Benefits - 3.5
Customer Service - 1

How can I do that, I have use array_unique, but it seems only work with 'label' not the 'scores'.

Thanks in Advance

like image 451
Mike Avatar asked Feb 20 '26 22:02

Mike


1 Answers

Reset variable $output_criterion in each outer iteration. Its concatenating all previous values.

$output = '';
foreach($arrays as $a){
    $output_criterion = '';
    $criterions_arr = $a['criterion'];
    foreach($criterions_arr as $c){
        $output_criterion .= $c['label'] . ' - ' . $c['scores'] . '<br/>';
    }
    $output .= $a['name'] . '<br/>' . $output_criterion . '<br/>';
}
echo $output;

Adding live demo : https://eval.in/608400

like image 50
Niklesh Raut Avatar answered Feb 23 '26 15:02

Niklesh Raut