Find the lowest value from an array

General discussions related to php

Moderators: egami, macek, gesf

Post Reply
breezue89
New php-forum User
New php-forum User
Posts: 3
Joined: Thu Mar 16, 2017 3:16 pm

Mon Oct 30, 2017 5:12 am

Hey guys,

How can I echo the name of one person with the lowest level in array like this?

Code: Select all

"test_subjects": {
		"5059844": {
			"name": "TylerDurden",
			"level": "25"
		},
		"4270364": {
			"name": "Bob",
			"level": "23"
		},
		"5536597": {
			"name": "gandalf",
			"level": "27"
		},
		"4762201": {
			"name": "Neo",
			"level": "21"
		},
		"2871510": {
			"name": "Sergey",
			"level": "21"
		}
	}
So I'd like to display either Sergey or Neo in this example.

should I order the array then use “end” to get the name of the last entry?

User avatar
hyper
php-forum Fan User
php-forum Fan User
Posts: 728
Joined: Mon Feb 22, 2016 5:52 pm

Mon Oct 30, 2017 2:03 pm

Once you change the syntax to PHP, it is one way of doing it.

thinsoldier
New php-forum User
New php-forum User
Posts: 24
Joined: Sat Dec 02, 2017 3:12 pm

Sat Dec 02, 2017 3:59 pm

Use json_decode to convert the json string into a php array. http://php.net/json_decode

Loop through the array and create a new array where "5059844" etc are the key and the "level" is the value.

Sort that new array by its value. http://php.net/asort

Get the first (or last) element in that array
http://php.net/manual/en/function.array-slice.php
http://php.net/manual/en/function.count.php

Get the key from that
http://php.net/manual/en/function.array-keys.php

Use the key you found to select the full info from the original array

echo $original["test_subjects"][ $key ]["name"};


... something roughly along those lines should work.

There's probably a way to do this in only 1 or 2 lines of code but I don't think that way so I can't tell you what it is.

Post Reply