[英]Separate multidimensional array into separate arrays
我正在努力使我對數組感興趣。
數組應如下所示:
$questions[$a] => array( [0] => No, comment1
[1] => Yes, comment2
[2] => No, comment3 )
$answer[$a] => array( [0] => No
[1] => Yes
[3] => No )
$comment[$a] => array( [0] => comment1
[1] => comment2
[3] => comment3 )
================================================== =======================
第二編輯:需要在循環中執行此操作以創建第三個數組-
if($answer[$a] == "Yes") { $display[$a] = "style='display:none'";
} else { $display[$a] = "style='display:block'"; }
這就是我所擁有的:(微型技術公司排名第28)
while ($a > $count)
{
if($count > 11) {
foreach($questions as $q) {
list($answer, $comments[]) = explode(',', $q);
if($answer === "Yes") {
$display[$a] = "style='display:none'";
} else {
$display[$a] = "style='display:block'";
}
$answers[] = $answer;
}
}
$a++;
}
如果它們實際上是字符串,則explode
原理如下:
$answers = array();
$comments = array();
$display = array();
foreach(array_slice($questions, 11) as $question) {
list($answer, $comments[]) = explode(',', $question);
$display[] = $answer === 'Yes' ? 'style="display: none"' : 'style="display: block"';
$answers[] = $answer;
}
將您的while循環更改為此
while ...
{
$parts = explode(',', $questions[$a]);
$answer[$a][] = trim($parts[0]);
$comment[$a][] = trim($parts[1]);
}
在原始代碼中,您每次都覆蓋$ answer [$ a]和$ comment [$ a],而不是追加到數組的末尾
$questions[$a] = array('Q1?' => 'A1', 'Q2?' => 'A2', 'Q3?' => 'A3');
foreach($questions[$a] as $key => $value)
{
$comment[$a][] = $key;
$answer[$a][] = $value;
}
這應該工作。
foreach ($questions[$a] as $key=>$value){
$temp = explode(',',$value);
$answer[$key] = $temp[0];
$comment[$key] = $temp[1];
}
$ key將分別具有0,1,2。 $ value將具有每個$ question [$ a]的值(否,Comment1 ....)
不能想到時髦的單缸紙,但是應該這樣做:
foreach ($questions as $a => $entries) {
foreach ($entries as $k => $entry) {
$parts = array_map('trim', explode(',', $entry));
$answer[$a][$k] = $parts[0];
$comment[$a][$k] = $parts[1];
}
}
這是正確的答案
foreach($questions as $key => $question){
foreach($question as $q => $data){
$data= explode(',',$data);
$comments[$key][$q] = $data[0];
$answer[$key][$q] = $data[1];
}
}
如果$questions
中的值是逗號分隔的字符串,則可以使用array_walk
函數填充$answer
和$comment
數組
$question = array(...); //array storing values as described
$answer = array();
$comment = array();
array_walk($question, function ($value, $key) use ($answer,$comment) {
$value_array = explode(',', $value);
$answer[$key] = $value_array[0];
$comment[$key] = $value_array[1];
});
請注意,這是使用需要PHP> = 5.3.0的匿名函數(關閉)顯示的。 如果您使用較低版本的PHP,則需要聲明一個命名函數,並在該函數中將$ answer和$ comment聲明為全局變量。 我認為這是一種不明智的方法(使用這樣的全局變量),因此,如果我使用的是PHP <5.3,我可能只會使用foreach循環,如對您的問題提出的其他答案。
諸如array_walk
, array_filter
類的函數以及使用回調的類似函數通常是利用匿名函數提供的靈活性的好地方。
$questions = array( 0 => 'No,comment1',1 => 'Yes,comment2',2 => 'No,comment3' );
foreach($questions as $question)
{
$parts = explode(",",$question);
$answer[] = $parts[0];
$comment[] = $parts[1];
}
echo "<pre>";
print_r($answer);
print_r($comment);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.