如何在数组中推送元素

时间:2014-05-09 16:30:41

标签: php arrays

array (size=2)
  0 => 
 array (size=8)
  'id' => string '66' (length=2)
  'room_name' => string 'Luxury' (length=6)
  'no_of_room' => string '0' (length=1)
  'price' => string '1000' (length=4)
  'description' => string 'dfh dvsrtruub  dsgd' (length=19)
  'image' => string 'arrow.jpg' (length=9)
  'hotel_id' => string '1' (length=1)

 1 => 
 array (size=8)
  'id' => string '65' (length=2)
  'room_name' => string 'Deluxe' (length=6)
  'no_of_room' => string '3' (length=1)
  'price' => string '800' (length=3)
  'description' => string 'rybsvssfd' (length=9)
  'image' => string '2P2Z4.png' (length=9)
  'hotel_id' => string '1' (length=1)

当我做var_dump时,这是我的数组。我想推动某些元素。我想要这样的东西:

array (size=2)
0 => 
array (size=8)
  'id' => string '66' (length=2)
  'room_name' => string 'Luxury' (length=6)
  'no_of_room' => string '0' (length=1)
  'price' => string '1000' (length=4)
  'description' => string 'dfh dvsrtruub  dsgd' (length=19)
  'image' => string 'arrow.jpg' (length=9)
  'hotel_id' => string '1' (length=1)
  'check_in_date'=> string '2014-1-1'(length=8)
  'check_out_date'=> string '2014-1-3'(length=8)
1 => 
array (size=8)
  'id' => string '65' (length=2)
  'room_name' => string 'Deluxe' (length=6)
  'no_of_room' => string '3' (length=1)
  'price' => string '800' (length=3)
  'description' => string 'rybsvssfd' (length=9)
  'image' => string '2P2Z4.png' (length=9)
  'hotel_id' => string '1' (length=1)
  'check_in_date'=> string '2014-1-1'(length=8)
  'check_out_date'=> string '2014-1-3'(length=8)

我想在每个数组的末尾添加两个元素。

两个要素是:

  'check_in_date'=> string '2014-1-1'(length=8)
  'check_out_date'=> string '2014-1-3'(length=8).

我试过:(假设我的数组名是$ jsonArray。

  $jsonArray = array_map(function ($subarray) {
  $subarray[] = "'check_in_date'=>'$check_in'";
  return $subarray;
  }, $jsonArray);
        var_dump($jsonArray);

但它对我不起作用。请帮我。提前谢谢。

1 个答案:

答案 0 :(得分:0)

这应该适用于您的check_in_date',' check_out_date'是静态的

$x=array(array('id'=>'66'),array('id'=>'67'));
$x=array_map('push_elements',$x);
function push_elements($arr){
$arr['check_in_date']='2014-1-1';
$arr['check_out_date']='2014-1-3';
return $arr;
}
var_dump($x);

这是输出: array(2){[0] => array(3){[" id"] =>字符串(2)" 66" [" CHECK_IN_DATE"] =>字符串(8)" 2014-1-1" [" CHECK_OUT_DATE"] =>字符串(8)" 2014-1-3" } [1] => array(3){[" id"] =>字符串(2)" 67" [" CHECK_IN_DATE"] =>字符串(8)" 2014-1-1" [" CHECK_OUT_DATE"] =>字符串(8)" 2014-1-3" }}