genesi5 genesi5 - 6 days ago 6
PHP Question

PHP, copying elements from multidimensional array to simple array

i need to copy inner elements from multidimmensional array of JSON to simple arrays.

For example:
json looks lie that:

{
"Point" : [
{"x": 0, "y": 37, "z": 93},
{"x": 1, "y": 81, "z": 44},
{"x": 2, "y": 31, "z": 91},
{"x": 3, "y": 45, "z": 6},
....
]
}


After json_parser, i need to copy each x, y and z to separate simple arrays like

x = array(1,2,3,4,...)
y = array(37,81,31,45,...), and so on.

Can you help me to solve that? i've tried everything i know or what i can understand - nothing works in the way i need.

Answer

You can try this:

<?php
error_reporting(0);
$str = '{
"Point" : [
    {"x": 0, "y": 37, "z": 93},
    {"x": 1, "y": 81, "z": 44},
    {"x": 2, "y": 31, "z": 91},
    {"x": 3, "y": 45, "z": 6}
]
}';
$array = json_decode($str,true);
$x = array();
$y= array();
$z= array();
foreach($array['Point'] as $single)
{
  $x[] = $single['x'];
  $y[] = $single['y'];
  $z[] = $single['z'];
}
print_r($x);
print_r($y);
?>
Comments