if ( $_GET['tab'] == 'newest' ) {
// Go through each question
foreach( array_reverse( $end_array, true ) as $tags_and_Qid['question_id'] => $titles_and_Qid['title'] )
{
// Grab the title for the first array
$title = $titles [ $tags_and_Qid['question_id'] ] ['title'];
// Grab the tags for the question from the second array
$tags = $end_array [ $tags_and_Qid['question_id'] ] ['tag'];
// Grab the username for the question from the second array
$username = $usernames [ $tags_and_Qid['question_id'] ] ['username'];
--- cut ----
}
}
Run Code Online (Sandbox Code Playgroud)
我经常需要使用这段代码.唯一的区别是array_reverse (..., true)第一个例子.
我试图通过创建一个函数organize_question来解决这个问题来解决这个问题.我没有成功:
function organize_questions ( $tab ) {
if ( $_GET['tab'] == 'newest' ) {
echo ( "array_reverse ( $end_array , true )" );
// Problem here!
}
if ( $_GET['tab'] == 'oldest' ) {
echo ( "$end_array" );
// this does not work
} else {
echo ( "array_reverse ( $end_array , true )" );
// Problem here!
}
}
Run Code Online (Sandbox Code Playgroud)
然后我将代码中的相关行更改为:
foreach( organize_question( $tab ) as $tags_and_Qid['question_id'] => $titles_and_Qid['title'] )
Run Code Online (Sandbox Code Playgroud)
问题在于将变量从一个函数转移到另一个函数.
我试图将所有必要的变量放在函数的参数中,但是一切都被破坏了,因为这个函数有很多依赖.
我是PHP的新手,所以必须有比我正在尝试的更简单的方法.
听起来这部分代码完成了大部分工作:
// Go through each question
foreach( array_reverse( $end_array, true ) as $tags_and_Qid['question_id'] => $titles_and_Qid['title'] )
{
-- cut ---
}
Run Code Online (Sandbox Code Playgroud)
我会将$_GET['tab']检查organize_questions()功能分开,并在其他地方做出参数决定.像这样:
function organize_questions($array)
{
foreach($array as $questionId => $title )
{
//do the work
}
}
Run Code Online (Sandbox Code Playgroud)
然后将您的决策制定代码放在其他地方:
if ( $_GET['tab'] == 'newest' )
{
organize_questions(array_reverse ( $end_array , true ));
}
else if ( $_GET['tab'] == 'oldest' )
{
organize_questions($end_array);
}
else
{
//etc.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1960 次 |
| 最近记录: |