Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

php - Any possible way to build arrays in one single line for http_build_query function?

Is there any possible way to dynamically build array in one single line to use it inside http_build_query function?

This would be one of scenarios:

//1. Initial array state
$array = array('value1' => 1);

//2. Clicks on "Sort by name ASC"
$array = array('value1' => 1, 'sort' => array('name' => 'ASC'));

//3. Clicks on "Sort by timestamp DESC"
$array = array('value1' => 1, 'sort' => array('name' => 'ASC', 'timestamp' => 'DESC'));

//4. Clicks on "Sort by name DESC"
$array = array('value1' => 1, 'sort' => array('name' => 'DESC', 'timestamp' => 'DESC'));

//5. Clicks on "Sort by timestamp ASC"
$array = array('value1' => 1, 'sort' => array('name' => 'ASC', 'timestamp' => 'ASC'));

This is what I tried so far:

http_build_query(array_merge($arr, array('sort' => array('email' => 'ASC'))));
http_build_query(array_merge($arr, array('sort' => array('timestamp' => 'ASC'))));

But of course, every time I use this line with different values, everything in $arr['sort'] is overwritten and only single value is kept there.

question from:https://stackoverflow.com/questions/65905563/any-possible-way-to-build-arrays-in-one-single-line-for-http-build-query-functio

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You will need to use sessions since you only send one parameter at a time. So, add a session_start() to all PHP files in your project. Set sort key inside the session and set the type values whenever you receive them. This way, previous choices are remembered until you explicitly destroy the session or unset the keys.

<?php

session_start();


/* 
 * Add additional isset checks for get parameters
*/


$sort_type = $_GET['sort'];
$sort_key  = array_keys($sort_type)[0];
$_SESSION['sort'][$sort_key] = $sort_type[$sort_key];

echo http_build_query(['sort' => $_SESSION['sort']]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...