我有多个数组,我希望在我的代码
下使用foreach
获取特定值
注意:未定义的索引:第52行的transId
$test = array(
'messages' => Array
(
'resultCode' => 'Ok',
'message' => Array
(
'code' => 'I00001',
'text' => 'Successful',
),
),
'transactionResponse' => Array
(
'responseCode' => '1',
'authCode' => 'Z7K31J',
'avsResultCode' => 'Y',
'cvvResultCode' => 'P',
'cavvResultCode' => '2',
'transId' => '40004672975',
'refTransID' => Array
(
),
'transHash' => '163382584395AB06470CF365AD6F7381',
'testRequest' => '0',
'accountNumber' => 'XXXX4242',
'accountType' => 'Visa',
'messages' => Array
(
'message' => Array
(
'code' => '1',
'description' => 'This transaction has been approved',
),
),
'transHashSha2' => Array
(
),
),
);
在我的数组上方,在foreach
中执行$test
我希望显示transid
,response
,transhash
foreach ($test as $key => $value) {
$response = $value['resultCode'];
$transId = $value['transId'];
$authCode = $value['authCode'];
$transHash = $value['transHash'];
}
答案 0 :(得分:0)
你不需要foreach:
$response = $test['messages']['resultCode'];
$transId = $test['transactionResponse']['transId'];
$authCode = $test['transactionResponse']['authCode'];
$transHash = $test['transactionResponse']['transHash'];
答案 1 :(得分:0)
使用array_walk_recursive()
,您不必进入数组的每个级别来回显您的值,如下所示:
<?php
array_walk_recursive($test, function ($item, $key){
if($key == 'transId' || $key == 'transHash' || $key == 'resultCode'){
echo $key." => ".$item."<br>";
}
});
答案 2 :(得分:0)
你可以用这个
foreach ($test as $key => $value)
{
if(!empty($value['message']))
{
$response = $value['messages']['resultCode'];
}
elseif(!empty($value['transactionResponse']))
{
$transId = $value['transactionResponse']['transId'];
$authCode = $value['transactionResponse']['authCode'];
$transHash = $value['transactionResponse']['transHash'];
}
}
如果你想要正确,那么你必须把它带到数组并键入你的transid