如何将数组添加到数组中

Str*_*uct 1 php arrays

我有一些带有一些数组的数组项.现在我想在数组项的顶部添加一个数组item_optional.

这是我尝试过的,但我认为这是不正确的:

$item_optional = array(
    'harry' => array('name'=>'test1', 'code'=>1697, 'hmp'=>'x1')
);

$items = array(
    'denise'  => array('name'=>'test2', 'code'=>2697, 'hmp'=>'x2'),
    'mike'    => array('name'=>'test3', 'code'=>3697, 'hmp'=>'x3'),
    'richard' => array('name'=>'test4', 'code'=>4697, 'hmp'=>'x4')
);

array_unshift($items, $item_optional);
Run Code Online (Sandbox Code Playgroud)

输出应该是:

$items = array(
    'harry'   => array('name'=>'test1', 'code'=>1697, 'hmp'=>'x1'),
    'denise'  => array('name'=>'test2', 'code'=>2697, 'hmp'=>'x2'),
    'mike'    => array('name'=>'test3', 'code'=>3697, 'hmp'=>'x3'),
    'richard' => array('name'=>'test4', 'code'=>4697, 'hmp'=>'x4')
);
Run Code Online (Sandbox Code Playgroud)

Kos*_*kis 5

你可以试试:

$item_optional = array(
    'harry' => array('name'=>'test1', 'code'=>1697, 'hmp'=>'x1')
);

$items = array(
    'denise'  => array('name'=>'test2', 'code'=>2697, 'hmp'=>'x2'),
    'mike'    => array('name'=>'test3', 'code'=>3697, 'hmp'=>'x3'),
    'richard' => array('name'=>'test4', 'code'=>4697, 'hmp'=>'x4')
);
Run Code Online (Sandbox Code Playgroud)

代码:

$items = $item_optional + $items;
Run Code Online (Sandbox Code Playgroud)

结果:

array (size=4)
  'harry' => 
    array (size=3)
      'name' => string 'test1' (length=5)
      'code' => int 1697
      'hmp' => string 'x1' (length=2)
  'denise' => 
    array (size=3)
      'name' => string 'test2' (length=5)
      'code' => int 2697
      'hmp' => string 'x2' (length=2)
  'mike' => 
    array (size=3)
      'name' => string 'test3' (length=5)
      'code' => int 3697
      'hmp' => string 'x3' (length=2)
  'richard' => 
    array (size=3)
      'name' => string 'test4' (length=5)
      'code' => int 4697
      'hmp' => string 'x4' (length=2)
Run Code Online (Sandbox Code Playgroud)