0

I'm working on my task right now, which accessing specific array when it is called by front end. My example data is like this

{
    "data": [
        {
            "name": "Jon Snow",
            "id": "01-0001",
        },
        {
            "name": "Robert Stark",
            "id": "01-0002"
        },
        {
            "name": "Sansa Stark",
            "id": "01-002333"
        },
        {
            "name": "Arya Stark",
            "id": "01-00012"
        },
        {
            "name": "Bran Stark",
            "id": "01-0003"
        },
         {
            "name": "Rickon Stark",
            "id": "01-0005"
        }

    ]
}

* In my front end I have this code *

 selectedEmployee: any=null;

    setActiveEmployee(employee: any) {
        this.selectedEmployee = employee;
        let myJSON = JSON.stringify(this.selectedEmployee);
        this.perEmpLateEarly();
    }

Whenever I choose the employee i get the id of that employee. So in this, if i choose "id": "01-0001" it will return the first array and it will keep the rest, and if I choose "id": "01-0002" it will return the second one and will keep the rest and so on. How can I do that in Php?

Thanks in advance

2
  • Where are you "choosing the id" ? frontend or backend ? Do you mean the ID is chosen on frontend and sent to backend ? Commented Oct 5, 2017 at 2:49
  • exactly. whenever i choose the id, it will send to backend to the get the data. @Pheonix; Commented Oct 5, 2017 at 2:52

1 Answer 1

1

You will do a GET/POST HTTP request from frontend, which would look something like this in

your_backend_page.php?id=<ID HERE>

Then the "your_backend_page.php" would look like as follows:

$list = {  "data": [ { .... }, { ...   }] } // this is the array you have

$idFromFrontEnd = $_GET["id"];

foreach ($list["data"] as $item) {   // iterate over all items
    if ($item["id"] == $idFromFrontEnd) {   // check if id matches
       echo json_decode($item);     // if matches, print this item
    }

}

Please note this approach is okay if you have a small number of items. For a larger list, you might want to have a database, where you can use sql to select.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.