New to PHP (from C#). I have an array ($metaarray), which if I json_encode() to the screen, it has this value:
[
{
"measure":"Walking","record":"steps","latestres":"6870","datet":"2022-08-31"
},{
"measure":"","record":"kilograms","latestres":"117","datet":"2022-09-12"
},{
"measure":"","record":"","latestres":null,"datet":"2022-09-12"
},{
"measure":"Walking","record":"steps","latestres":"6840","datet":"2022-09-12"
},{
"measure":"Bodyweight","record":"kilograms","latestres":"92","datet":"2022-09-12"
},{
"measure":"Benchpress","record":"kilograms","latestres":"90","datet":"2022-09-12"
}
]
Is there an easy way for me to iterate through the metaarray - or to easily reference a record - eg. I would normally do something like:
$latestres = $metaarray[0][2];
...which should be "6870" - however it doesn't return any result when I do that.
Is there a way I can easily reference a particular value (eg. first record, "latestres" or 3rd value) in the above array?
CodePudding user response:
I don't know if this helps you, but $data[2]
does not represent third item in an array, unless the array happens to be created linearly (called a list). In PHP, 2
is actually the key to a map (name/value pair). So unless there is actually a key with that index, you can't access it. You can see a demo of what I'm talking about here.
You can get around the feature/limitation by using one of the tricks from this answer: https://stackoverflow.com/a/24825397/231316
function getNthItemFromArray(array $array, int $idx)
{
return $array[array_keys($array)[$idx]];
}
Obviously you'd add some guards.
As everyone notes, you should really start with your data before the encode. However, assuming that for whatever you have a JSON string, you can tell the decoder to give you an associative array instead of an object. Putting that all together you could do something like:
$json = <<<EOT
[
{
"measure":"Walking","record":"steps","latestres":"6870","datet":"2022-08-31"
},{
"measure":"","record":"kilograms","latestres":"117","datet":"2022-09-12"
},{
"measure":"","record":"","latestres":null,"datet":"2022-09-12"
},{
"measure":"Walking","record":"steps","latestres":"6840","datet":"2022-09-12"
},{
"measure":"Bodyweight","record":"kilograms","latestres":"92","datet":"2022-09-12"
},{
"measure":"Benchpress","record":"kilograms","latestres":"90","datet":"2022-09-12"
}
]
EOT;
$decoded = json_decode($json, true);
echo getNthItemFromArray($decoded[0], 2);
function getNthItemFromArray(array $array, int $idx)
{
return $array[array_keys($array)[$idx]];
}
Demo here: https://3v4l.org/POdma