0

So I have the following JSON Object as an example:

 {

  "employees": {
    "employee300": {
      "number" : "example",
      "Name" : "example",
      "position" : 1
    },
    "employee456": {"number" : "example",
      "Name" : "example",
      "position" : 2},
    "employee120":{"number" : "example",
      "Name" : "example",
      "position" : 3}
}
}

I only have the position and I want to get the employee's id. For example, I have the position number that is 2 and I need to get the id that is "employee456".

I know there are a lot of key functions in PHP, but I would like to know how I can make my code work in my scenario. I can also convert the json to an array if there is a solution to it that way.

2 Answers2

1

I'm not sure whether you want to do this in JS or PHP, going to assume the latter.

<?php function get_employee_at_pos($employees, $pos)
{
    foreach ($employees as $key => $value) {
        if ($value['position'] == $pos) {
            return $key;
        }
    }
    return false;
}
MarkM
  • 798
  • 6
  • 17
0

use var keys = Object.keys(obj) to get the keys, then use the myobject[keys[1]]. (1 corresponds to position - 1).

EDIT: in php

$keys = array_keys(myobject); and use $myobject[$keys[1]]

EDIT 2: in php, you need to load the json in an array

$myjson = json_decode(file_get_contents("yourfile.json"), true); // loads yourfile.json and converts to a php array.