Skip to content
Advertisement

how to loop and array to create a TABLE in laravel with phpdocx

I am using phpdocx to generate an array with my data in a docx format.

$contact is an array of multiple object. Sometimes $contact contain 1 object, and sometimes more.

I want to make a loop, to add contact as much as I need.

My problem : For exemple, If I am doing this I will get an error like “Undefined array key 3” if my contact data only contain 3 object or less.

important : Here, if my datas contain 4 object (from 0 to 3 ) it will work but doesn’t work when i have 2 objects.

 $contact= array(
      array(
        'name' => $request->get('contact')[0]['name'],
        'userName' =>  $request->get('contact')[0]['userName'],
        'number' =>  $request->get('contact')[0]['number'],
        'mail' =>  $request->get('contact')[0]['mail'],
      ),
        array(
        'name' => $request->get('contact')[1]['name'],
        'userName' =>  $request->get('contact')[1]['userName'],
        'number' =>  $request->get('contact')[1]['number'],
        'mail' =>  $request->get('contact')[1]['mail'],
      ),    
      array(
        'name' => $request->get('contact')[2]['name'],
        'userName' =>  $request->get('contact')[2]['userName'],
        'number' =>  $request->get('contact')[2]['number'],
        'mail' =>  $request->get('contact')[2]['mail'],
      ), 
      array(
        'name' => $request->get('contact')[3]['name'],
        'userName' =>  $request->get('contact')[3]['userName'],
        'number' =>  $request->get('contact')[3]['number'],
        'mail' =>  $request->get('contact')[3]['mail'],
      ),

    );


$docx->replaceTableVariable($contact, array('parseLineBreaks' => true));

what i am actually trying with no success for the moment : https://www.phpdocx.com/en/forum/default/topic/1773

Advertisement

Answer

I have make a loop and it is now working

  $contactData =    $request->get('contact');
$contactTab = array();
for ($i = 0; $i < count($contactData); $i++) {
  $rowData = array(
     'name' => $contactData[$i]['name'],
    'userName' =>  $contactData[$i]['userName'],
    'number' =>  $contactData[$i]['number'],
    'mail' =>  $contactData[$i]['mail'],
  );
  $contactTab[] =   $rowData;
}

  $docx->replaceTableVariable($contactTab, array('parseLineBreaks' => true));
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement