0

I'm trying to create an array with Laravel but customise some of the values.

For example, if I was to return $user->rounds this would return

"data": [
    {
        "id": 3,
        "name": "sample name"
    },
    {
        "id": 4,
        "name": "sample name 2"
    }
]

I want to customise the return to something like

"data": [
    {
        "id": 3,
        "name": "sample name",
        "extra": "Extra Detail"
    },
    {
        "id": 4,
        "name": "sample name 2",
        "extra": "Extra Detail"
    }
]

I'm trying to do it, by the following code:

$data = array();

foreach ($user->rounds as $r) {
    $data = [
        'id' => $r->id,
        'name' => $r->name,
        'extra' => 'Test Extra'
    ];
}

return $data;

But it returns only one round while it should be returning 3.

1
  • 5
    You're overwriting $data on each loop. I assume you wanted to do $data[] = ... notice the extra [] after data. Commented Sep 30, 2016 at 10:34

2 Answers 2

1

You need to add array to $data array with each iteration:

$data[] = [
    'id' => $r->id,
    'name' => $r->name,
    'extra' => 'Test Extra'
];

Also, you could use array_push() function for that.

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

Comments

0

Try to do like this

$data = array();
$i=0;
foreach($user->rounds as $r){
  $data[$i] = [
    'id' => $r->id,
    'name' => $r->name,
    'extra' => 'Test Extra'
  ];
  $i++;
}
return $data;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.