1

I have a string containing that is being returned from an API which is dynamic, an example of the string is below:

[[[1473261033000,3.7933],[1473312464000,2.0295],[1473313206000,2.0844],[1473313505000,1.4888],[1473313805000,1.3003],[1473314105000,1.1164]]]

I cant really do anything with it like this so i would like to split it into 2 arrays, one for the first number and one for the second, like so:

Array1

  • 1473261033000
  • 1473312464000
  • 1473313206000
  • 1473313505000
  • 1473313805000
  • 1473314105000

Array2

  • 3.7933
  • 2.0295
  • 2.0844
  • 1.4888
  • 1.3003
  • 1.1164

Would someone help me out on how i could go about this? its driving me nuts.

BigJobbies
  • 3,633
  • 11
  • 43
  • 66

2 Answers2

5

You need to first decode the JSON string into an array, then use array_column to extract the two arrays.

This will require PHP >=5.5, but if you require a lower version then you should be able to find a backwards compatible version of the function on the documentation page.

<?php
$str = '[[[1473261033000,3.7933],[1473312464000,2.0295],[1473313206000,2.0844],[1473313505000,1.4888],[1473313805000,1.3003],[1473314105000,1.1164]]]';
$json = json_decode($str, true)[0];

$first = array_column($json, 0);
$second = array_column($json, 1);

print_r($first);
print_r($second);

See https://eval.in/637961 for a demo.

iainn
  • 16,826
  • 9
  • 33
  • 40
0

Well! json_decode() turns it to an array. Whether it's any use to you depends on what you want to do with the data really, doesn't it?

I'm wondering why you want to split it in two arrays. Isn't it easier to keep it in one?

<?php
    $val = '[[[1473261033000,3.7933],[1473312464000,2.0295],[1473313206000,2.0844],[1473313505000,1.4888],[1473313805000,1.3003],[1473314105000,1.1164]]]';

    $myData = json_decode($val);

    var_dump($myData);
?>
Ben Hillier
  • 2,126
  • 1
  • 10
  • 15