E
E
Evgeny Yalovoy2020-10-07 09:41:41
PHP
Evgeny Yalovoy, 2020-10-07 09:41:41

How to fill array key with values ​​of another php array?

Good afternoon, please tell me how to merge two arrays into one?
First array:

$allSpecCat = [];

        foreach($specsCatId as $sci)
        {
          $allSpecCat = [
                 'blog_cat_id' => $sci->id,
                ];
        }


Second array:
$data = [
                 'name'        => $name,
                 'guid'        => $idspec,
                 'blog_cat_id' => '',
                 'created_at'  => date("Y-m-d H:i:s"),
                 'updated_at'  => date("Y-m-d H:i:s"),
                ];


Tried to combine them like this:
$res = array_merge($data, $allSpecCat);    
        var_dump($res);

But the first array entry in data['blog_cat_id'] is written with an empty value.

Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2020-10-07
@Kushelbek

data['blog_cat_id']remains empty because the array is $dataone-dimensional, and $allSpecCat- two-dimensional.
array_mergedoes not find the corresponding keys from the array $datain the array $allSpecCat, and therefore adds $datato the resulting array unchanged. Then the values ​​from the array $allSpecCatwith numerical indices are added to the end of the resulting array.

So it's clear that I want to transfer the values ​​from $allSpecCat['blog_cat_id'] to $data['blog_cat_id'].

# если $allSpecCat - двумерный массив и нужно получить все значения из него
$data['blog_cat_id'] = array_map(function($v) {
  return $v['blog_cat_id'];
}, $allSpecCat);

# если $allSpecCat - ассоциативный массив
$data['blog_cat_id'] = $allSpecCat['blog_cat_id']

F
FanatPHP, 2020-10-07
@FanatPHP

You yourself decide first, you combine , or replace .
If you merge, then an empty entry should remain.
if you stupidly stupidly put in data['blog_cat_id'] what is in $allSpecCat, then you just need to stupidly put in data['blog_cat_id'] what is in $allSpecCat

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question