-1

I have the following array $data. n and 0 are identical, it's just the way the data is returned. I need to determine the max and min values for the id value, it looks like the id values are stored as strings, how is this achieved?

Array
(
    [0] => stdClass Object
        (
            [n] => artefact[10.3]{"id": "1", "name": "001", "type": "Artefact"}
            [0] => artefact[10.3]{"id": "1", "name": "001", "type": "Artefact"}
        )

    [1] => stdClass Object
        (
            [n] => artefact[10.4]{"id": "2", "name": "002", "type": "Artefact"}
            [0] => artefact[10.4]{"id": "2", "name": "002", "type": "Artefact"}
        )

    [2] => stdClass Object
        (
            [n] => artefact[10.5]{"id": "3", "name": "003", "type": "Artefact"}
            [0] => artefact[10.5]{"id": "3", "name": "003", "type": "Artefact"}
        )

)
Spatial Digger
  • 1,883
  • 1
  • 19
  • 37
  • The output of `var_dump` and `print_r` are of little use. Instead, try [`var_export`](https://php.net/var_export), which can help in creating an [mcve]. Please also read the other [help] articles, especially "[ask]". – outis Oct 28 '22 at 21:24

1 Answers1

1

It seems that {"id":....} is a JSON value, and we need to parse the value and collect IDs. Before we need to clean artefact string with preg_replace function. In this case, we can determine max and min values:

<?php

$data = [
    [
         '0'=>'artefact[10.3]{"id": "1", "name": "001", "type": "Artefact"}',
         'n'=>'artefact[10.3]{"id": "1", "name": "001", "type": "Artefact"}',
    ],
    [
         '0'=>'artefact[10.4]{"id": "1", "name": "001", "type": "Artefact"}',
         'n'=>'artefact[10.4]{"id": "3", "name": "001", "type": "Artefact"}',
    ],
];


$ids = [];

foreach ($data as $datum) {

    foreach ($datum as $item) {
        $parsedItem = preg_replace("/artefact\[(.+?)\]/",'',$item);
        $jsonDecoded = json_decode($parsedItem);
        $ids[] = $jsonDecoded->id;
    }
}

$maxId = $ids ? max($ids):0;
$minId = $ids ? min($ids):0;

echo "Max id: $maxId <br> Min id $minId ";
Tural Rzaxanov
  • 783
  • 1
  • 7
  • 16