0

consider below array:-

Array
(
[0] => Array
    (
        [0] => 99895
        [1] => 35378
        [2] => 0.01

    )

[1] => Array
    (
        [0] => 99895
        [1] => 813
        [2] => -0.97

    )

[2] => Array
    (
        [0] => 99895
        [1] => 771
        [2] => 0.29

    )

[3] => Array
    (
        [0] => 442
        [1] => 833
        [2] => -1.06

    )

[4] => Array
    (
        [0] => 442
        [1] => 485
        [2] => -0.61

    )

[5] => Array
    (
        [0] => 442
        [1] => 367
        [2] => -0.14

    )

[6] => Array
    (
        [0] => 442
        [1] => 478
        [2] => 0.77

    )

[7] => Array
    (
        [0] => 442
        [1] => 947
        [2] => -0.07

    )

[8] => Array
    (
        [0] => 7977
        [1] => 987
        [2] => 0.76

    )

[9] => Array
    (
        [0] => 7977
        [1] => 819
        [2] => 0.37

    )

[10] => Array
    (
        [0] => 7977
        [1] => 819
        [2] => 0.36

    )

[11] => Array
    (
        [0] => 7977
        [1] => 653
        [2] => 1.16

    )

[12] => Array
    (
        [0] => 7977
        [1] => 1653
        [2] => 1.15
    )

)

from the above array how will I determine the below array?

array
(
    99895 => -0.223

    442 => -0.22

    7977 => 0.76
)

Actually I need the average value of column 3 in respect of column 1.

6
  • Write a loop that collects each column 3 into an array keyed off column 1. Then calculate the average of each of those arrays. Commented Dec 20, 2013 at 10:07
  • @Barmar not able to do. will You help me plz. Commented Dec 20, 2013 at 10:09
  • Why aren't yo able to do it? It's just simple looping and array indexing? I know, you're a total noob, you never really learned how to program, you need everything spoon fed to you. I'm already in the middle of writing the answer for you. Commented Dec 20, 2013 at 10:10
  • @Barmar no Barmer. I'm also trying. Commented Dec 20, 2013 at 10:12
  • SO questions are supposed to include what you tried, so we can help you understand where you went wrong. Not just ask for code to be written for you. Commented Dec 20, 2013 at 10:13

1 Answer 1

2

First collect all the column 3 elements into an array keyed off column 1:

$arrays = array();
foreach ($input as $vals) {
    $key = $vals[0];
    $val = $vals[2];
    if (isset($arrays[$key])) {
        $arrays[$key][] = $val;
    } else {
        $arrays[$key] = array($val);
    }
}

Now go through all of them, calculating the averages:

foreach ($arrays as &$array) {
    $array = array_sum($array)/count($array);
}
Sign up to request clarification or add additional context in comments.

Comments

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.