开发者

how to rebuild PHP 2 dimentional array?

开发者 https://www.devze.com 2022-12-20 01:12 出处:网络
i have 2 dimentional array like this: $day_array = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,开发者_JAVA百科4,5]];

i have 2 dimentional array like this:

$day_array = [[1,2,3,4,5],[1,2,3,4,5],[1,2,3,4,5],[1,2,3,开发者_JAVA百科4,5]];

and i want to rebuild like this

$day_array = [[1,1,1,1][2,2,2,2][3,3,3,3][4,4,4,4,4][5,5,5,5]];

Any ideas on how to do this?

Thanks in advance...


$day_array = array(array(1,2,3,4,5),array(1,2,3,4,5),array(1,2,3,4,5),array(1,2,3,4,5));

$output = array();
for ( $y = 0; $y < count($day_array[0]); $y++ ) {
    for ( $x = 0; $x < count($day_array); $x++ ) {
        $output[$y][] = $day_array[$x][$y];
    }
}

print_r($output);

Version which outputs a string:

$data = '[';
for ( $y = 0; $y < count($day_array[0]); $y++ ) {
    $data .= '[';
    $output = array();
    for ( $x = 0; $x < count($day_array); $x++ ) {
        $output[] = $day_array[$x][$y];
    }
    $data .= implode(',', $output) . ']';
}
$data .= ']';

echo $data;


Why do you want the result as an array? You are actually trying to extract the information: How many of each value do I have? You can use the value as array key to achive that:

$result = array();
foreach ($day_array as $innerArray) {
    foreach ($innerArray as $value) {
        if (!isset($result[$value])) {
            $result[$value] = 0;
        }
        $result[$value]++;
    }
}
var_dump($result);
# Will output:
# array(5):
#   1 => 4,
#   2 => 4,
#   3 => 4,
#   4 => 4,
#   5 => 4
0

精彩评论

暂无评论...
验证码 换一张
取 消