0

I have an excel file whose data is a 3d array.

enter image description here

I am using PHPExcel Object to return the data into 3d array. But I can only return a 2d array.

    $objPHPExcel = PHPExcel_IOFactory::load($file);
    $cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
    foreach ($cell_collection as $cell) {
        $column = $objPHPExcel->getActiveSheet()
        ->getCell($cell)
        ->getColumn();
        $row = $objPHPExcel->getActiveSheet()
        ->getCell($cell)
        ->getRow();
        $data_value = $objPHPExcel->getActiveSheet()
        ->getCell($cell)
        ->getValue();
        if ($row == 1) {
            $header[$row][$column] = $data_value;
        } else {
            $arr_data[$row][$column] = $data_value;
        }
  }

How can I return a result array like this:

$res = array(
    [2]=>array(
        [A] => A,//column A
        [B] =>array([1]=>'red',[2]=>'pink',[3]=>'purple')
     ),
    [3]=>array(
        [A] => B,//column B
        [B] =>array([1]=>'white',[2]=>'blue',[3]=>'black')
     ),
);

Anyone knows how I could modify my code to return the expected result? Any answer would be appreciated!

1 Answer 1

1

I am not a php programmer and this code not complied. Here I have added my code to generate your expected array. It can help you to solve your problem. I think $column is a column value like A,B.....

 $i = 1;
 $i_str = "";
 $res = array();
 foreach ($cell_collection as $cell) {

        $column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
        $row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
        $data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();

        if ($row == 1) {
            $header[$row][$column] = $data_value;
        } else {

            if($column == 'A' && $data_value != ""){
                $i++;
                $i_str = (string) $i;
                $res[$i_str]['A'] = $data_value;
                $res[$i_str]['B'] = array();

            }
            else if($column == 'B'){
                $len = (string) (count($res[$i_str]['B']) + 1);
                $res[$i_str]['B'][$len] = $data_value;

            }

        }
  }

  print_r($res) // here you will get your expected 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.