看看这段代码:
$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不能这样工作)
当前回答
我想把我的答案补充到表格中,如下:
//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);
希望这能帮助到一些人
其他回答
例子array_merge()……
$array1 = array("color" => "red", 2,4); $ array2 =阵列(“a”、“b”、“颜色”= >“绿色”、“形状”= >“梯形”,4); $result = array_merge($array1, $array2); print_r(结果);
阵列([color] = >绿色,[0]= > 2,[1]= > 4,[2]= >,[3]= > b(形状)= >梯形,[4]= > 4,)
有点晚了,但如果你不介意嵌套数组,你可以采用这种方法:
$main_array = array(); //Your array that you want to push the value into
$value = 10; //The value you want to push into $main_array
array_push($main_array, array('Key' => $value));
澄清一下, 如果你输出json_encode($main_array),看起来像[{"Key":"10"}]
将值压入数组会自动为其创建一个数字键。
当向数组添加键-值对时,您已经拥有键,不需要为您创建一个键。将键推入数组是没有意义的。只能设置数组中特定键的值。
// no key
array_push($array, $value);
// same as:
$array[] = $value;
// key already known
$array[$key] = $value;
我想知道为什么最简单的方法还没有公布:
$arr = ['company' => 'Apple', 'product' => 'iPhone'];
$arr += ['version' => 8];
这里已经给出了一些很好的例子。只是添加了一个简单的例子,将关联数组元素推到根数值索引索引。
$intial_content = array();
if (true) {
$intial_content[] = array('name' => 'xyz', 'content' => 'other content');
}