fbc
3 months ago
109
3
Laravel

How do you filter results from an Array without changing the structure of the array?

Posted 3 months ago by fbc

I query an API that gives me a results in an array like this: dd($latestrtfeed) give me:

array:1 [▼
  "readMeter" => array:2 [▼
    "Requested" => 1
    "ReadSet" => array:1 [▼
      0 => array:10 [▼
        "Meter" => "350002874"
        "Group" => 65244221
        "Interval" => 60
        "Protocol" => "v4"
        "MAC_Addr" => "xx:xx:xx:00:03:0a"
        "Tz_Offset_Sec" => 0
        "Bad_Reads" => 6
        "Good_Reads" => 994
        "Credits" => 1000000
        "ReadData" => array:1000 [▼
          0 => array:5 [▼
            "Good" => 1
            "Date" => "2019-08-13"
            "Time" => "21:28:04.778"
            "Time_Stamp_UTC_ms" => 1565731684778
            "kWh_Tot" => "8227.50"
          ]
...

the bad_reads throw my charts off.

So I need to filter all ['readMeter']['ReadSet']['0']['ReadData']['Good'] == 0 out of the array.

So I tried using the following query first, to copy all the GOOD reads into a new array but that did not work.

$latestrtfeed2 = $latestrtfeed->where(['readMeter']['ReadSet']['0']['ReadData']['Good'] == 1)->get();

then I tried the foreach below, but could not find the right command to make that happen.

        /* Copy good records to a new array */
        foreach ($latestrtfeed as $record) {
        /* Skip any records which are not good */
            if ($record['ReadSet']['0']['ReadData']['Good'] == 0) {
                continue;
            }
            /* Copy this record to new array */
            $latestrtfeedFiltered[] = $record;
        }

This example I think is the closest I have gotten but I end up with a "Undefined index: Good" error.

Any ideas would be helpful.

Please sign in or create an account to participate in this conversation.