看看这段代码:

$GET = array();    
$key = 'one=1';
$rule = explode('=', $key);
/* array_push($GET, $rule[0] => $rule[1]); */

我正在寻找这样的东西:

print_r($GET);
/* output: $GET[one => 1, two => 2, ...] */

有函数来做这个吗?(因为array_push不能这样工作)


当前回答

不,关联数组没有等价的array_push(),因为没有办法确定下一个键。

你必须使用

$arrayname[indexname] = $value;

其他回答

佩卡就是这么说的…

或者,你也可以像这样使用array_merge:

array_merge($_GET, array($rule[0] => $rule[1]));

但我更喜欢Pekka的方法,因为它更简单。

不,关联数组没有等价的array_push(),因为没有办法确定下一个键。

你必须使用

$arrayname[indexname] = $value;

可以使用联合运算符(+)组合数组,并保留所添加数组的键。例如:

<?php

$arr1 = array('foo' => 'bar');
$arr2 = array('baz' => 'bof');
$arr3 = $arr1 + $arr2;

print_r($arr3);

// prints:
// array(
//   'foo' => 'bar',
//   'baz' => 'bof',
// );

因此,您可以执行$_GET += array('one' => 1);。

关于联合操作符与array_merge使用的更多信息,请参阅http://php.net/manual/en/function.array-merge.php的文档。

我想把我的答案补充到表格中,如下:

//connect to db ...etc
$result_product = /*your mysql query here*/ 
$array_product = array(); 
$i = 0;

foreach ($result_product as $row_product)
{
    $array_product [$i]["id"]= $row_product->id;
    $array_product [$i]["name"]= $row_product->name;
    $i++;
}

//you can encode the array to json if you want to send it to an ajax call
$json_product =  json_encode($array_product);
echo($json_product);

希望这能帮助到一些人

我想知道为什么最简单的方法还没有公布:

$arr = ['company' => 'Apple', 'product' => 'iPhone'];
$arr += ['version' => 8];