JSON - Display only certain data in php

94
November 07, 2018, at 2:00 PM

This is my json data as an array, and it is in the file data.json, I tried to parse the data using php, but I am not able show the result using a for loop.

array (
  'data' => 
  array (
    0 => 
    array (
      'a' => 3222,
      'b' => 3,
    ),
    1 => 
    array (
      'a' => 3221,
      'b' => 3,
    ),
    2 => 
    array (
      'a' => 2215,
      'b' => 2,
    ),
    3 => 
    array (
      'a' => 2214,
      'b' => 2,
    ),
    4 => 
    array (
      'a' => 3218,
      'b' => 2,
    ),
    5 => 
    array (
      'a' => 3217,
      'b' => 3,
    ),
    6 => 
    array (
      'a' => 3216,
      'b' => 3,
    ),
    7 => 
    array (
      'a' => 1235,
      'b' => 1,
    ),
    8 => 
    array (
      'a' => 1234,
      'b' => 1,
    ),
    9 => 
    array (
      'a' => 1233,
      'b' => 1,
    ),
    10 => 
    array (
      'a' => 3213,
      'b' => 3,
    )
)

I want to display only the data, which is "b=3" which contains the maximum value of "a".

Here is my code, which displays all the results of "a" as a string. All the data is shown as a list.

<?php
    $json = file_get_contents('data.json');
    $data = json_decode($json,true);
    $q = $data['data'];
    $length = count($q);
    for ($i = 0; $i<$length ; $i++){
        if ($q[$i]['b']==3){
            $pc = $q[$i]['a'];
            echo $pc;
            echo "<br>";    
        }
    }

This is not the result I was expected.

Answer 1

One way to solve this could be to check the current value of $pc against the latest value; If that is higher, then overwrite it:

$q = $data['data'];
$length = count($q);
$max = 0;
for ($i = 0; $i<$length ; $i++){
    if ($q[$i]['b']==3){
        $pc = $q[$i]['a'];
        if ($pc > $max) {
            $max = $pc;
        }
    }
}
echo $max; //3222

Another option could be to use array_map and max:

$result = max(array_map(function($x){
    if($x['b'] === 3) return $x['a'];
    }, $q
));
echo $result; //3222 
READ ALSO
Autocomplete is not working on mobile when using Semantic UI

Autocomplete is not working on mobile when using Semantic UI

I am facing a weird issueI am using semantic ui and due to some unknown reasons autocomplete is not working for mobile but working perfectly on desktop browsers

100
Group similar object values in array javascript

Group similar object values in array javascript

I have initial data like this :

114
Multiple condition in match use $or or $and

Multiple condition in match use $or or $and

I know this has been asked before but I can't seem to find the answer, i wannt to filter show with flag 1, flag 2, in $or for seacrhing

109
MDC TextField, how to fix outline for user/password fields?

MDC TextField, how to fix outline for user/password fields?

I use outlined mdc text-field https://material-componentsgithub

219