transform string into multidimensional array

Asked

Viewed 115 times

0

I have the string down and I’ve tried to turn it into a Multidimensional array but I don’t know how to do it, another problem I can’t solve is the spaces, even using a explode they remain in the array. any help is welcome.

The multidimensional array I want is this:

Array(2) ( [0] => Array ( [0] => 12/ 8/2008 [1] => 0 [2] => maria [3] =>  online) [1] => Array ([0] => 13/ 5/2013 [1] => 0 [2] => joão [3] => off));

My code.

$string = "0/ 0/0  0  maria online 0/ 0/0  0  joão off"; 

$ar = explode(" ", $string);

print_r($ar);
  • If you know the function explodes, and you probably know the repetition structures, I think you have to work on the programming logic now!

  • A question the date you add as? Or the date already comes in the string? The command trim($variavel) removes the spaces at the beginning and end of the variable. Because if you have these separate data and group, you are like $string = "0/0/00 maria online 0/0/00 joão off"; it is better to separate afterwards.

2 answers

0

Thanks for the help Vinicius, with your encouragement I managed to do so.

 $string = "0/ 0/0  0  maria online 0/ 0/0  0  joão off"; 
 $explode = explode(" ", $string);
 foreach ($explode as $explode) {
 if($explode != ""){
        $dbArrayy[] = $explode; 
 }        
};

$result = array_chunk($dbArrayy, 5);

print_r($result); 


//resultado
Array ( [0] => Array ( [0] => 0/ [1] => 0/0 [2] => 0 [3] => maria [4] => online ) [1] => Array ( [0] => 0/ [1] => 0/0 [2] => 0 [3] => joão [4] => off ) ) 

0


I think there’s a better way, but I couldn’t think straight about it. but I think what I did will do.

<?php

$string = "0/ 0/0  0  maria online 0/ 0/0  0  joão off"; 
$count = 0;
$ar = explode(" ", $string);
foreach ($ar as $ar) {
    if($ar != ""){
        if ($count <= 4) {
            $dbArray[0][] = $ar;
        }else{
            $dbArray[1][] = $ar;
        }
        $count++;
    }
}

/*
versão sem loopping ou condicionais
$dbArray = [
    0 => [
        0 => $ar[0].$ar[1],
        1  => $ar[3],
        2 => $ar[5],
        3 => $ar[6]
    ],
    1 => [
        0 => $ar[7].$ar[8],
        1  => $ar[10],
        2 => $ar[12],
        3 => $ar[13]
    ]
];
*/
var_dump($dbArray);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.