Ahmad Badpey
Ahmad Badpey

Reputation: 6622

access to properties of an array contain json formatted elements in laravel

suppose I have an Array like this :

$myArray =
[
    {
        "id": 86,
        "name": "admin/login"
    },
    {
        "id": 87,
        "name": "admin/logout"
    },
    {
        "id": 88,
        "name": "admin/desktop"
    }
]

Each element of array has json format. and now I want to get name of element that have id of 87 for example.

Firstly How can I found that is there element with this id then get name property of that?

Upvotes: 0

Views: 228

Answers (3)

Rumel
Rumel

Reputation: 319

Your $myArray is incorrect so, assuming it is a json string you can do this in the following way :

  1. At first json_decode it into an arry.
  2. Loop through the elements to find out you desired value(87).
  3. Keep a flag which will tell if you have actually found any value.

    <?php
    
    $myArray =
    '[
        {
            "id": 86,
            "name": "admin/login"
        },
        {
            "id": 87,
            "name": "admin/logout"
        },
        {
            "id": 88,
            "name": "admin/desktop"
        }
    ]';
    
    $myArray = json_decode($myArray , true);
    
    $found = 0;
    
    foreach($myArray as $anArray)
    
    
    {
    
        if($anArray['id'] == 87)
        {
             var_dump($anArray['name']);
             $found = 1;
        }
    }
    
    if($found == 1)
    {
         var_dump("Element found.");
    }
    else
    {
         var_dump("Element not found. ");
    }
    
    ?>
    

Upvotes: 0

Rene Korss
Rene Korss

Reputation: 5494

Decode JSON string into array. Then use Laravel's array_first method.

<?php
$myArray = '[{"id": 86,"name": "admin/login"},{"id": 87,"name": "admin/logout"},{"id": 88,"name": "admin/desktop"}]';

// Decode into array
$array = json_decode($myArray, true);

// Find item with correct id
$result = array_first($array, function($key, $value){
  return $value['id'] === 87;
}, false);

if ($result) {
    echo 'Item found, it\'s name is: '.$result['name'];
}

If you have id you like to find in variable, you have to use use construct.

// ID to search for
$searchID = 87;

// Find item with correct id
$result = array_first($array, function($key, $value) use($searchID){
  return $value['id'] === $searchID;
}, false);

Upvotes: 1

Marko Milivojevic
Marko Milivojevic

Reputation: 579

Try using this:

$newArray = json_decode($myArray);

and you'll get type of array

[
    [
        "id"=> 86,
        "name"=> "admin/login"
    ],.....
    ........
]

Upvotes: 0

Related Questions