MariaJen MariaJen - 6 months ago 28
PHP Question

how to push data in array object using php


I expected this kind of data


0 => array:3 [
0 => "12"
1 => "2017-03-28 05:29:56"
2 => "2017-03-29 05:29:56"
]
1 => array:3 [
0 => "10"
1 => "2017-03-28 05:29:56"
2 => "2017-03-29 05:29:56"
]



but I always come up to this kind of data


array: [
0 => "10"
1 => "2017-03-28 05:29:56"
2 => "2017-03-29 05:29:56"
3 => "12"
4 => "2017-03-28 05:29:56"
5 => "2017-03-29 05:29:56"
]



this is the code that I try, I just want to transfer the data on $data to $new_data, but it always give different result, and I don't know how to reconstruct my code


$data =[
0 => array:3 [
0 => "Employee ID"
1 => "time_in (YYYY-MM-DD HH:mm:ss)"
2 => "time_out (YYYY-MM-DD HH:mm:ss)"
]
1 => array:3 [
0 => "10"
1 => "2017-03-28 05:29:56"
2 => "2017-03-29 05:29:56"
]
2 => array:3 [
0 => "12"
1 => "2017-03-28 05:29:56"
2 => "2017-03-29 05:29:56"
]
3 => false
]
$new_data=[];

for ($i=1; $i < $len-1; $i++) {
for ($x=0; $x < 3 ; $x++) {

array_push($new_data,$data[$i][$x]);

}
}


do please help me on my logic, I'm just new in array

Answer Source

You have an array $new_data, and you push six single new items. That's why you get one single array with six items.

If you change it to this, you get what you want:

for ($i = 1; $i < $len - 1; $i++) { 
     $new_item = [];
     for ($x = 0; $x < 3; $x++) {
         array_push($new_item, $data[$i][$x]);
     }
     array_push($new_data, $new_item);
}

This way, you push three items to a new array, and then push this array to your $new_data.

After I've seen your edit: You can also do this:

for ($i = 1; $i < $len - 1; $i++) { 
     array_push($new_data, $data[i]);
}

You don't need to iterate through the three single items if you always want to push the complete block.

Or, since you only want to seem to remove the first and last entry:

unset($data[0]);
array_splice($data, count($data), 1); // Remove last entry and rebuild indices.