Home  >  Q&A  >  body text

Modify a specific value in an array

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粉253800312P粉253800312251 days ago428

reply all(1)I'll reply

  • P粉297434909

    P粉2974349092024-01-17 15:37:35

    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'];
    }

    reply
    0
  • Cancelreply