Problem adding a date to an array index

Asked

Viewed 37 times

3

I’m passing a date inside an index of a Array. As the looping is being performed, this Array is being fed. The index is also generated through this looping. However, when printing the index, it displays only 1 character (as if it were "fragmented" within the Array). I think it’s a simple mistake, but I’m beating myself up for not going through it yet.

$pcb_data = array();
while($r = $DB->fetchArray($result)){  
    $pcb_cmb_id = $r['pcb_cmb_id'];


    $pcb_data[$pcb_cmb_id] = date("d/m/Y",  strtotime($r['pcb_data']));
}

If I print $pcb_data[4], for example, it will display "2" instead of a date (ex: 12/12/1988).

Note: I cut the while pq code the rest of the information is not relevant, in this case.

Can someone help me, please?

  • Of a print_($pcb_data); after the while, put in the comments after

  • 1

    It was found that the variable of the array was being overwritten by other information, probably created for previous tests... Thank you for the aid.

3 answers

3


I tried to replicate the same mistake but without success, see :

<?php 
$pcb_data = array();
$i = 0;

while($i < 2){                          
  $pcb_data[$i] = date("d/m/Y",  strtotime('2000-10-10'));
  $i++;
}

Exit

Array
(
  [0] => 10/10/2000
  [1] => 10/10/2000
)

Obs: I tried emulating in different versions of PHP here

The data coming from the bank is correct ?

This index you accessed actually has this rule ?

Have any log or error showing ?

  • It was found that the variable of the array was being overwritten by other information, probably created for previous tests... Thank you for the aid.

1

Try this, I think you’ll find out where the problem is occurring:

function formatDate($data) {
   return implode('-',array_reverse(explode("-", $data)));
}

$pcb_data = array();

while($r = $DB->fetchArray($result)){  
    $pcb_cmb_id = $r['pcb_cmb_id'];
    $pcb_data[] = array(
            'id'  => $r['pcb_cmb_id'],
            'data'=>  formatDate($r['pcb_data'])
           ); 
}

echo '<pre>';
print_r($pcb_data);
  • 1

    It was found that the variable of the array was being overwritten by other information, probably created for previous tests... Thank you for the aid.

-1

$pcb_data = array();
while($r = $DB->fetchArray($result)){
    $pcb_data[$r['pcb_cmb_id']] = date("d/m/Y",  strtotime($r['pcb_data']));
}

echo '<pre>';
print_r($pcb_data);
echo '<pre>';

There is no need to create variables for everything. It already puts directly inside the array key and its value.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.