看看这段代码:
$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不能这样工作)
当前回答
我通常这样做:
$array_name = array(
'key1' => 'value1',
'key2' => 'value2',
'key3' => 'value3'
);
其他回答
我想把我的答案补充到表格中,如下:
//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);
希望这能帮助到一些人
2023
有很多答案。有些有用,有些不错,但有些尴尬。因为你不需要复杂而昂贵的算术运算,循环等简单的操作,如添加一个元素到数组,这里是我的一行添加到数组的函数集合。
$array = ['a' => 123, 'b' => 456]; // init Array
$array['c'] = 789; // 1.
$array += ['d' => '012']; // 2.
$array = array_merge($array, ['e' => 345]); // 3.
$array = [...$array, 'f' => 678]; // 4.
print_r($array);
// Output:
/*
Array
(
[a] => 123
[b] => 456
[c] => 789
[d] => 012
[e] => 345
[f] => 678
)
*/
在99%的情况下,我使用版本1。($array['c'] = 789;)但我喜欢版本4。这是带有splat操作符的版本(https://www.php.net/manual/en/migration56.new-features.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($arr, ['key1' => $value1, 'key2' => value2]);
这工作得很好。 在数组中创建键及其值
有点奇怪,但这对我很管用
$array1 = array("Post Slider", "Post Slider Wide", "Post Slider");
$array2 = array("Tools Sliders", "Tools Sliders", "modules-test");
$array3 = array();
$count = count($array1);
for($x = 0; $x < $count; $x++){
$array3[$array1[$x].$x] = $array2[$x];
}
foreach($array3 as $key => $value){
$output_key = substr($key, 0, -1);
$output_value = $value;
echo $output_key.": ".$output_value."<br>";
}