T
T
Tvis20102017-05-16 14:00:37
Laravel
Tvis2010, 2017-05-16 14:00:37

How to concatenate 2 arrays in php?

The bottom line is this:
There are 2 arrays, the first one is simply numbered:

$clear = [];
      for ($i = 1; $i <= 10; $i++) {
        $clear[] = [
                                'mesto' => $i,
                            ];
      }

It looks like this:
spoiler
ff57930d14b34794ba78bf3dcc809353.png

The second from the database with values
$mesta2 = \DB::table('mesta')->where('game_id', 595)->get();

Looks like that:
spoiler
7e11d35d172742d89625b8b7fd80b23f.png

The target is to append to an empty array i.e. first, information from the second by 'mesto'
To get something like this:
spoiler
4390287ffaa84750929ea8cbee9539e3.png

Tried array_merge($clear,$mesta2); Just adds to the end
Tried $clear+$mesta2 just nothing happens
If you can write the code right away)

Answer the question

In order to leave comments, you need to log in

4 answer(s)
T
Tvis2010, 2017-05-20
@Tvis2010

Did so

$mesta2 = \DB::table('mesta')
      ->where('game_id', $gameId)
      ->join('users', 'mesta.user_id64', '=', 'users.id64')
          ->select(['mesta.*','users.username as username','users.avatar as avatar'])
      ->get();  

      $clear = [];
for ($i = 1; $i <= $game->mest_all; $i++) {
      $find = 0;		     
             foreach($mesta2 as $mestos) {
                if($find == 0) {
                    if($mestos->mesto == $i) {
                        $find++;
            $i++;
            $clear[] = $mestos;
          }
        }			
      }
  $clear[] = [
                'mesto' => $i,
               ];
}
$mesta = json_encode($clear);

A
Alexander Pushkarev, 2017-05-16
@AXP-dev

It fails because $mesta2 is a collection, not an array.

$clear = ...;
$mesta2 = ...;
$result = array_merge($clear, $mesta2->toArray())

A
Alex Teterin, 2017-05-16
@errogaht

$clear = [];
for ($i = 1; $i <= 10; $i++) {
    $clear[] = [
        'mesto' => $i,
    ];
}

$mesta2 = \DB::table('mesta')->where('game_id', 595)->get()->keyBy('mesto');
$result = \Illuminate\Support\Collection::make($clear)->map(function ($item) use ($mesta2) {
    if ($persistedItem = $mesta2->get($item['mesto'])) {
        return $persistedItem;
    }
    return $item;
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question