Modify a specific value in an array
P粉253800312
P粉253800312 2024-01-16 22:25:40
0
1
484

I have an array and the data is obtained from a SQL query. The array is saved in a variable named $users. look:

<?php
    
    ...

    $data = array();
    $data['users'] = $users;
    $data['status']= true;
    $this->format_json($data);
    
?>

This is the result I get:

{
    "users":[
        {
            "id":"1",
            "name":"Joana",
            "avatar":"uploads/avatar/0eff31cdfa4d2b32c49e97dec010cc31_thumb.png"
        }
    ],
    "status":true
}

I want to know how to add a link at the beginning of "avatar", for example:

{
    "users":[
        {
            "id":"1",
            "name":"Joana",
            "avatar":"https://sitename.com/uploads/avatar/0eff31cdfa4d2b32c49e97dec010cc31_thumb.png"
        }
    ],
    "status":true
}

I tried foreach but I don't know how to use it correctly in this case. I don't know how to override the $users array mentioned above.

thank you all!


edit

The problem is solved like this:

foreach ($users as $key => $entry) {
    $users[$key]->avatar = "https://sitename.com/" . $entry->avatar;
}
$data = array();
$data['users'] = $users;
$data['status']= true;
$this->format_json($data);

P粉253800312
P粉253800312

reply all(1)
P粉297434909

You can use foreach to loop through the user array. The & operator before $value will allow you to modify array items directly without indexing.

foreach ( $data['users'] as &$value ) {
  $value['avatar'] = 'https://sitename.com/' . $value['avatar'];
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template