0

I have this array:

Array
(
    [1] => 20130701 4 4 3060 1
    [2] => 20130702 270 757 13812810 4
    [3] => 20130703 5 123 3894971 2
    [4] => 20130704 290 478 5119617 1
    [5] => 20130705 88 98 189791 2
    [6] => 20130708 9 73 564627 1
    [7] => 20130722 6102 11992 41974701 1
    [8] => 20130723 6397 11021 40522224 1
    [9] => 20130725 4644 9336 49167728 2
    [10] => 20130726 4891 10157 33516844 3
    [11] => 20130727 123 319 2538226 3
    [12] => 20130728 451 801 1078705 2
    [13] => 20130729 13609 30407 95551827 5
    [14] => 20130730 6354 17550 272794650 158
    [15] => 20130731 6270 18456 269468599 174
)

I'm trying to change the output in order to show it in a chart, do i change it into a json:

foreach ($day as $key => $value) {
    $value = explode(" ", $value) ; 
    $day[$key] = $value ; 
    $charts[] = array(substr($value[0],0,4).'-'.substr($value[0],4,2).'-'.substr($value[0],6,2),$value[4]) ; 
}
$charts = json_encode($charts, JSON_NUMERIC_CHECK) ;

But it displays me this :

[["2013-07-01","1\r"],["2013-07-02","4\r"],["2013-07-03","2\r"],["2013-07-04","1\r"],["2013-07-05","2\r"],["2013-07-08","1\r"],["2013-07-22","1\r"],["2013-07-23","1\r"],["2013-07-25","2\r"],["2013-07-26","3\r"],["2013-07-27","3\r"],["2013-07-28","2\r"],["2013-07-29","5\r"],["2013-07-30","158\r"],["2013-07-31","174\r"]] 

why \r does show? any way I can prevent this ?

2
  • 2
    that's a carriage return char, and probably comes from wherever you got this data from initially. e.g. you need to trim() your array members.
    – Marc B
    Mar 6, 2014 at 14:49
  • 1
    Can you do a var_dump() rather than print_r of your array? Mar 6, 2014 at 14:51

2 Answers 2

1

try

$charts[] = array(substr($value[0],0,4).'-'.substr($value[0],4,2).'-'.substr($value[0],6,2),substr($value[4],0, -1)) ; 
1

You have return characters at the end of your array

[3] => 20130703 5 123 3894971 2\r

They are not visible because \n = new line \r returns the pointer to the beginning of the line.

Your best bet is to use trim() on every element:

foreach ($day as $key => $value) {
    $value = explode(" ", trim($value)); 
    $day[$key] = trim($value) ; 
    $charts[] = array(trim(substr($value[0],0,4).'-'.substr($value[0],4,2).'-'.substr($value[0],6,2),$value[4])) ; 
}

It's even better on numbers to use intval(), which ensures datatype to be integer and removes blankspaces, returns, ... too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.