Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Multiple Looping to generate new Array

I have some arrays which looks like below

 array(
    [0] =>
        array( ['direction'] =>  '0.000,0.160,0.123,0.104,0.000' )
    [1] =>
        array( ['direction'] =>  '0.000,0.101,0.237,0.101,0.000' )
    [2] =>
        array( ['direction'] =>  '0.000,0.160,0.125,0.163,0.000' )
  )

with for loop, I would like to generate new array which would looks like

data1 = [0.000, 0.000, 0.000]
data2 = [0.160, 0.101, 0.160]
data3 = [0.123, 0.237, 0.125]
data4 = [0.104, 0.101, 0.163]
data5 = [0.000, 0.000, 0.000]

which means with for loop, I would like to get each column of value then assign that value to each new array.

what I tried to do is

$cnt = count($array);
$buildCnt = count($array['direction']);
for($i = 0; $i < $cnt; $i++){
    for($j = 0; $j < buildCnt; $j++){
     'i need to do something here
    }
}

anyone help me please?? Thanks

like image 895
Kyungmo Kim Avatar asked Aug 05 '26 17:08

Kyungmo Kim


2 Answers

I don't know if there is a better way thru array functions by you can just also use a normal foreach loop. Like this:

$original_array = array(
    array('direction' => '0.000,0.160,0.123,0.104,0.000'),
    array('direction' => '0.000,0.101,0.237,0.101,0.000'),
    array('direction' => '0.000,0.160,0.125,0.163,0.000'),
);
$new_array = array();
foreach($original_array as $sub_array) {
    // loop each sub array
    $pieces = explode(',', $sub_array['direction']);
    // explode by comma
    foreach($pieces as $key => $piece) {
        // each piece, push by data(n)
        $new_array["data".($key+1)][] = $piece;
        // if you don't want to use extract
        // ${"data".($key+1)}[] = $piece;
    }
}

extract($new_array); // import newly created sub arrays
echo '<pre>';
print_r($data1); // $data2, $data3, ... and so on

$data1 should look like:

Array
(
    [0] => 0.000
    [1] => 0.000
    [2] => 0.000
)
like image 143
Kevin Avatar answered Aug 08 '26 10:08

Kevin


$arr = array(array( 'direction' =>  '0.000,0.160,0.123,0.104,0.000' ),array( 'direction' =>  '0.000,0.101,0.237,0.101,0.000' ),array( 'direction' =>  '0.000,0.160,0.125,0.163,0.000' ));
foreach($arr AS $dirArr){
  $dirs = explode(",",$dirArr['direction']);
  for($i = 0; $i < count($dirs); $i++) $data[$i][] = $dirs[$i];
}

and if you really need them to be those variable names...

$data1 = $data[0];
$data2 = $data[1];
$data3 = $data[2];
$data4 = $data[3];
$data5 = $data[4];
like image 37
dano Avatar answered Aug 08 '26 10:08

dano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!