2017-06-05 132 views
1

我有多个阵列,我想特别价值得到使用foreach我下面的代码PHP数组如何在数组值获取使用的foreach

注意:未定义指数:TRANSID在上线52

$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显示值,responsetranshash

foreach ($test as $key => $value) { 
    $response = $value['resultCode']; 
    $transId = $value['transId']; 
    $authCode = $value['authCode']; 
    $transHash = $value['transHash']; 
} 
+0

'$值“transactionResponse”] [“TRANSID”]' – hassan

+0

@Janak维亚斯确实想只是形成第二阵“transactionResponse” ? –

+1

你不能用你想要的foreach。您在消息数组中没有transId,authCode或transHash,并且还有transactionResponse数组中的resultCode。 –

回答

0

使用array_walk_recursive(),你不必在数组中的每个级别去呼应类似下面的值:

<?php 
    array_walk_recursive($test, function ($item, $key){ 
    if($key == 'transId' || $key == 'transHash' || $key == 'resultCode'){ 
     echo $key." => ".$item."<br>"; 
    } 
}); 
0

你不需要的foreach:

$response = $test['messages']['resultCode']; 
$transId = $test['transactionResponse']['transId']; 
$authCode = $test['transactionResponse']['authCode']; 
$transHash = $test['transactionResponse']['transHash']; 
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