转换数组laravel

时间:2018-06-09 10:05:38

标签: arrays laravel laravel-5 laravel-5.1 laravel-collection

我使用Laravel框架,我有一个数组:

[▼
  "0.022" => "24.00000000"
  "0.013" => "506.00000000"
  "0.041" => "65.00000000"
]

你能帮我把它转换成这样的新格式:

[▼
  0 => {▼
    "xxx": 0.022
    "yyy": 24.00000000
  }
  1 => {▼
    "xxx": 0.013
    "yyy": 506.00000000
  }
  2 => {▼
    "xxx": 0.041
    "yyy": 65.00000000
  }
]

非常感谢。

3 个答案:

答案 0 :(得分:1)

$inputArray=array(
  "0.022" => "24.00000000"
  "0.013" => "506.00000000"
  "0.041" => "65.00000000"
);



 $outputArray=array();

 foreach($inputArray as $key=>$val)
 { 
   $obj['xxx']= $key;
   $obj['yyy']= $val;
   array_push($outputArray,$obj)
 }

 echo $outputArray;

答案 1 :(得分:1)

$array = [
"0.022" => "24.00000000",
"0.013" => "506.00000000",
"0.041" => "65.00000000"
];

$data=array();
foreach($array as $key=>$value)
{
    $data[]= ['xxx'=>$key,'yyy'=>$value];
}

echo "<pre>";
echo(json_encode($data));

答案 2 :(得分:1)

根据您的输出,您需要增量索引作为键

$item = [
   '0.022' => '24.00000000',
   '0.013' => '506.00000000',
   '0.041' => '65.00000000'
];

$output = [];
$count = 0;
foreach($item as $key => $value) {
    $output[$count]['xxx'] = $key;
    $output[$count]['yyy'] = $value;
    $count++;
}

echo json_encode($output);