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
266 views
in Technique[技术] by (71.8m points)

php - Turn an array of values into an array of variables

Update

After the initial feedback I got that my question is unclear, I decided to start over and ask it with more context, and clearer details. See Many php mysqli queries from one prepared statement without knowing how many parameters

Sorry about the confusion.

Original Question

I'd like to dynamically turn an associative array:

$array =
[
    'key' => 'AX-2NV',
    'id' => 2
]

into an array of variables:

[$key,$id] // where $key='AX-2NV' and $id=2

When I have no control over the input array. The variable creation is simple enough with the extract function

extract($array); // will create the variables $key and $id

The challenge is how do I get the resulting variables in an array when I don't know ahead of time what the variable names or the input array size will be?

This may be irrelevant but the objective is to make a call to the function call_user_func_array and pass it the array [$key,$id] as the parameters of the function I'm calling. I've considered doing simply

call_user_func_array($function,array_values($array));

But I still need a handle to these variables for further processing, so just using the values and moving on is not an option.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can make an array containing a list of all the keys from another array with array_keys().

extract() may have security implications, I hope this is some sort of hypothetical problem because otherwise you should be fetching the data you need from the array itself, and not converting its items into global variables.


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

...