PHP代码优化:处理空数组并返回JSON状态
您可以通过在迭代之前检查 'trc20' 数组是否为空来优化代码。如果为空,您可以返回一个 JSON 响应,并将状态设置为 'error'。以下是一个示例:
if (empty($item['trc20'])) {
$responseData = array(
'status' => 'error',
'message' => 'trc20 array is empty'
);
} else {
foreach ($item['trc20'] as $trc20) {
foreach ($trc20 as $tokenAddress => $value) {
if ($tokenAddress === 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t') {
$value /= 1000000;
$responseData[] = array(
'address' => $address,
'status' => 'success',
'USDT' => $value
);
}
}
}
}
// 返回 JSON 格式的响应
echo json_encode($responseData);
在此示例中,如果 'trc20' 数组为空,则响应将为:
{
"status": "error",
"message": "trc20 array is empty"
}
否则,它将返回包含给定令牌地址的 USDT 值的响应。
原文地址: https://www.cveoy.top/t/topic/qqsq 著作权归作者所有。请勿转载和采集!