重新排列数组的值?

时间:2013-12-03 02:47:00

标签: php arrays

我有这两个数组

array1 = (Q1, Q2)
array2 = (ansA1,ansB1,ansC1,ansD1,ansA2,ansB2,ansC2,ansD2)

我使用array_merge合并了这两个数组 所以它现在

combine_array = (Q1,Q2,ansA1,ansB1,ansC1,ansD1,ansA2,ansB2,ansC2,ansD2)

我需要重新排列这些数组,其中Q2将放在'ansA2'之前 我知道在指定键值时可以轻松完成,但如果在数组中有更多值,该怎么办?例如,。 Q1,到Q10等。感谢您的帮助

3 个答案:

答案 0 :(得分:1)

所以你想要一个键到值的映射,但是平坦,没有键的任何值都应该放在数组的末尾?

好。我们可以滥用array_map

$result = [];

array_map(function($key, $value) use (&$result) {
    if ($key !== null) {
        array_push($result, $key);
    }

    array_push($result, $value);
}, $keys, $values);

Demo

我认为使用MultipleIterator可以使它更清晰(或至少5.2兼容):

$result = [];

$iter = new MultipleIterator(MultipleIterator::MIT_NEED_ANY);
$iter->attachIterator($keys);
$iter->attachIterator($values);

foreach ($iter as $pair) {
    list($key, $value) = $pair;

    if ($key !== null) {
        array_push($result, $key);
    }

    array_push($result, $value);
}

答案 1 :(得分:1)

更明智的做法是

$questions[1]['question'] = "What is 2 + 2?";
$questions[1]['answers']['a'] = 1;
$questions[1]['answers']['b'] = 2;
$questions[1]['answers']['c'] = 3;
$questions[1]['answers']['d'] = 4;

$questions[2]['question'] = "What is 3 + 3?";
$questions[2]['answers']['a'] = 2;
$questions[2]['answers']['b'] = 4;
$questions[2]['answers']['c'] = 6;
$questions[2]['answers']['d'] = 8;

甚至就像这个一样简单

$questions[1]['question'] = "What is 2 + 2?";
$questions[1]['a'] = 1;
$questions[1]['b'] = 2;
$questions[1]['c'] = 3;
$questions[1]['d'] = 4;

答案 2 :(得分:0)

嗯...不太确定你是否正在使用关联数组,但是根据你所描述的合并两个平面数组的文字问题来解决这个问题。

$array1 = array('Q1', 'Q2');
$array2 = array('ansA1','ansB1','ansC1','ansD1','ansA2','ansB2','ansC2','ansD2');

$combine_array = array();
foreach ($array1 as $key1 => $value1) {
  $combine_array[] = $value1;
  foreach ($array2 as $key2 => $value2) {
    if ("Q" . preg_replace('/[^0-9]/is', '', $value2) == $value1) {
      $combine_array[] = $value2;
    }
  }
}

echo '<pre>';
print_r($combine_array);
echo '</pre>';

print_r()的输出应如下:

Array
(
    [0] => Q1
    [1] => ansA1
    [2] => ansB1
    [3] => ansC1
    [4] => ansD1
    [5] => Q2
    [6] => ansA2
    [7] => ansB2
    [8] => ansC2
    [9] => ansD2
)

我的另一个想法是创建一个关联数组,其中问题数组值作为键,并且数组值中的答案连接到该键。像这样:

$array1 = array('Q1', 'Q2');
$array2 = array('ansA1','ansB1','ansC1','ansD1','ansA2','ansB2','ansC2','ansD2');

$combine_array = array();
foreach ($array1 as $key1 => $value1) {
  $answer_array = array();
  foreach ($array2 as $key2 => $value2) {
    if ("Q" . preg_replace('/[^0-9]/is', '', $value2) == $value1) {
      $answer_array[] = $value2;
    }
    $combine_array[$value1] = $answer_array;
  }
}

echo '<pre>';
print_r($combine_array);
echo '</pre>';

输出结果为:

Array
(
    [Q1] => Array
        (
            [0] => ansA1
            [1] => ansB1
            [2] => ansC1
            [3] => ansD1
        )

    [Q2] => Array
        (
            [0] => ansA2
            [1] => ansB2
            [2] => ansC2
            [3] => ansD2
        )

)