7

我搜索了如何同时推送键和值,我发现了这个:如何将值和键都推送到数组中

但我的问题是如何将多个键和值添加到数组中?

$somearray

Array ( 
[id] => 1645819602 
[name] => Michael George) 

我想将此添加到$somearray

[first_name] => Michael 
[last_name] => George
[work] => Google

所以输出将是

Array ( 
    [id] => 1645819602 
    [name] => Michael George
    [first_name] => Michael 
    [last_name] => George
    [work] => Google) 

我知道这段代码行不通

$arrayname[first_name] = Michael;
$arrayname[last_name] = George;
$arrayname[work] = Google;

任何帮助将不胜感激。谢谢

4

7 回答 7

6

您必须将数组键括在引号中,如果它是字符串,则还必须将值括起来。如果值是整数,则不需要将值括在引号中。但如果它是字符串,则必须将值括在引号中。所以你需要像这样更改他的代码

$arrayname['first_name'] = 'Michael';
$arrayname['last_name'] = 'George';
$arrayname['work'] = 'Google';
于 2013-10-30T08:22:24.930 回答
1

这会给你的想法:

<?

$array = array(
         [id] => 1);

$array["hello"] = "world";

print_r($array); //prints Array (
                             [id] => 1,
                             [hello] => "world")


?>
于 2013-10-30T08:23:33.143 回答
1

将值添加到数组中的语法,

$ArrayName['IndexName'] = $elementValue;
于 2013-10-30T08:30:13.070 回答
1

这就是我将一个数组中的所有元素添加到另一个数组的方式:

<?php
$oneArray = ['d', 'e', 'f'];
$anotherArray = ['a', 'b', 'c'];

array_push($anotherArray, ...$oneArray);
//['a', 'b', 'c', 'd', 'e', 'f'];
于 2021-04-24T22:43:32.350 回答
0

试试这个:

Here you need to add quotes to wrap index.

<?php
$arrayname['first_name'] = 'Michael';
$arrayname['last_name'] = 'George';
$arrayname['work'] = 'Google';
?>

Always use this when assigning any value in the array.
  • 谢谢
于 2013-10-30T08:34:51.590 回答
0

quote分配值时不要忘记输入。

$arrayname[first_name] = 'Michael';
$arrayname[last_name] = 'George';
$arrayname[work] = 'Google';
于 2013-10-31T03:00:23.200 回答
0
$ac_re_arr['date']      = array();
$ac_re_arr['amt']       = array();

$sql5   = mysql_query(" SELECT `id`,`bank_dues_amt`,`bank_dues` FROM `tbl_act` where `bank_dues_amt` !='' and `case_id`='$case_id' ")or die(mysql_error());
while($data5    = mysql_fetch_array($sql5))
{
    $amt3       = explode('$',$data5['bank_dues_amt']);
    $date3      = explode('$',$data5['bank_dues']);
    $k          = 0;
    foreach($amt3 as $key3)
    {
        array_push($ac_re_arr['date'],$date3[$k]);
        array_push($ac_re_arr['amt'],$amt3[$k]);
        $k++;
    }
}
print_r($ac_re_arr);

像这样输出

数组([日期] => 数组([0] => 10-08-2017 [1] => 15-07-2016)[amt] => 数组([0] => 5000 [1] => 2000) )

于 2018-08-01T05:27:13.653 回答