简体   繁体   中英

how to rebuild PHP 2 dimentional array?

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,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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM