执行php echo作为参数值

时间:2018-11-05 13:10:22

标签: php

我有以下代码,并且正在手动生成tracking_id值,并且工作正常:

<?php

$data = [
"client_reference_id" => "ABCD",
"tracking_id" => "1234",
];
$data = json_encode($data);

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$curl_response = curl_exec($curl);
curl_close($curl);
echo $curl_response ."\n";

结果:

{“响应”:[{“ tracking_id”:“ 1234”,}],

现在我需要动态创建tracking_id。...所以我尝试如下:

"tracking_id" => "$r = 'DOCC'. mt_rand(0000000001,9999999999); echo $r;",

我得到了以下结果:

{“响应”:[{“ tracking_id”:“ ='DOCC'。mt_rand(0000000001,9999999999);回声;”,“

但是我应该获得一些随机数作为tracking_id。...

表示参数中的php代码不起作用。...

3 个答案:

答案 0 :(得分:2)

由于您需要10位随机数:

function randomNumber($length) {
$result = '';

for($i = 0; $i < $length; $i++) {
    $result .= mt_rand(1, 9);
}

return $result;
}

$data = [
"client_reference_id" => "ABCD",
"tracking_id" => 'DOCC'.randomNumber(10);//no need to echo, just assign it
];
$data = json_encode($data);

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$curl_response = curl_exec($curl);
curl_close($curl);
echo $curl_response ."\n";

答案 1 :(得分:0)

重构您的代码:

$r = 'DOCC'. mt_rand(0000000001,9999999999);

$data = [
  "client_reference_id" => "ABCD",
  "tracking_id" => $r,
];

答案 2 :(得分:0)

只需将$ data数组替换为以下内容即可。

$data = [
"client_reference_id" => "ABCD",
"tracking_id" => 'DOCC'.  mt_rand(0000000001,9999999999),
];