看看这段代码:
$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不能这样工作)
看看这段代码:
$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不能这样工作)
当前回答
简单的方法:
$GET = array();
$key = 'one=1';
parse_str($key, $GET);
http://php.net/manual/de/function.parse-str.php
其他回答
可以使用联合运算符(+)组合数组,并保留所添加数组的键。例如:
<?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的文档。
array_push($GET, $GET['one']=1);
这对我很管用。
我想把我的答案补充到表格中,如下:
//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);
希望这能帮助到一些人
嗨,我也有同样的问题,我找到了这个解决方案,你应该使用两个数组,然后将它们结合起来
<?php
$fname=array("Peter","Ben","Joe");
$age=array("35","37","43");
$c=array_combine($fname,$age);
print_r($c);
?>
参考:w3schools
将值压入数组会自动为其创建一个数字键。
当向数组添加键-值对时,您已经拥有键,不需要为您创建一个键。将键推入数组是没有意义的。只能设置数组中特定键的值。
// no key
array_push($array, $value);
// same as:
$array[] = $value;
// key already known
$array[$key] = $value;