简体   繁体   中英

Convert array to another character [php]

I have data in the form:

$data = Array ( [0] => 1 [1] => 4 [2] => 3 [3] => 3 )

I want to convert it to:

$x = [[1], [2], [3], [4]];

I do not know how to do this?

I'm using the library PHP-ML ( http://php-ml.readthedocs.io/en/latest/machine-learning/regression/least-squares/ ).

If you want to create array from values, you can do it this way:

$x = [];
foreach($data as $key => $value) {
  array_push($x, $value);
}

If you want to create array of arrays from values you can edit it like this:

$x = [];
foreach($data as $key => $value) {
  array_push($x, [$value]);
}
$data = array(0 => "0", 1  => "1", 2  => "2", 3  => "3");
$output;
$halt = count($data) - 1;
for($i = 0; $i < count($data); $i++){
  if($i==$halt){
        $output.="[".$data[$i]."]";
    }else{
        $output.="[".$data[$i]."]".", ";
    }
}
$x = "[".$output."]";
echo $x;

Like so?

But why change array to array?

  • Ahhh I see, You want it in a json format?*

    $array = array( 0 => [1], 1 => [2] , 2 => [3], 3 => [3] );

    $x = json_encode($array, JSON_HEX_APOS);

    echo $x;

[[1],[2],[3],[3]]

$data = array(1,4,3,3);

$x = '[['.implode('], [', $data).']]';

echo $x;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM