0

I'd like to convert this array:

Array
(
    [5] => 3.5
    [6] => 4.5
    [7] => 5.5

)
Array
(
    [8] => 5
    [9] => 6
    [10] => 7

)

Into a two-dimensional array that would look like this:

$array = array(
"a" => array("3.5","4.5", etc.),
"b" => array("5","6", etc.),
);

I think I'm getting close with the following code, but I'm still missing a name such as "a" and "b" for each array group:

$array = array($result);
echo '<pre>';
print_r(array_chunk($array,2, true));
echo '</pre>';

Here is the code from where I'm getting the two arrays :

$period = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);
$sma = array(6,9);

foreach ($sma as $range)    {

    $sum = array_sum(array_slice($period, 0, $range));
    $result = array($range - 1 => $sum / $range);

    for ($i = $range, $n = count($period); $i != $n; ++$i) {

        $result[$i] = $result[$i - 1] + ($period[$i] - $period[$i - $range]) / $range;

    }

    $array = array($result);
    echo '<pre>';
    print_r(array_chunk($array,2, true));
    echo '</pre>';
} 
7
  • 2
    You just did it didn't you!? Commented Mar 22, 2018 at 15:54
  • 1
    PS: That looks like 2 arrays Commented Mar 22, 2018 at 15:54
  • 1
    $array = array("a" => $firstArray, "b" => $secondArray); Simple Commented Mar 22, 2018 at 15:56
  • 1
    Agree with @RiggsFolly, with addition of array_values() (seems to want to loose keys in final array). Commented Mar 22, 2018 at 15:58
  • 1
    You had better show us a print_r($result) so we know what we are dealing with here. Note- edit that into your question - DONT post as a comment Commented Mar 22, 2018 at 15:59

1 Answer 1

1
    $period = array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);

    $sma = array(6,9);

    $array = array();

    foreach ($sma as $range)    {

    $sum = array_sum(array_slice($period, 0, $range));

    $result = array($range - 1 => $sum / $range);

    for ($i = $range, $n = count($period); $i != $n; ++$i) {

    $result[$i] = $result[$i - 1] + ($period[$i] - $period[$i - $range]) / $range;

    }

//add each array to final array
    $array[] = $result;

    } 
    echo '<pre>';
    print_r($array);
    echo '</pre>';
Sign up to request clarification or add additional context in comments.

1 Comment

Good answers will always have an explanation of what was done and why it was done that way, not only for the OP but for future visitors to SO that may find this question and be reading your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.