从包含关联数组PHP

时间:2018-11-11 17:10:16

标签: php arrays

我需要使用PHP读取名为 orders.log 的文件的内容并使用变量。日志文件的存储方式如下:

Array
(
    [time] => 2099-99-99 00:00:00
    [gateway] => Paypal
    [gatewayOK] => Yes
    [gatewayTransactionId] => XXXXXXX
    [POST] => Array
        (
            [mc_gross] => 9.99
            [protection_eligibility] => Eligible
            [address_status] => confirmed
            [payer_id] => XXXXX
            [address_street] => XXXXX
            [payment_date] => 00:00:00 Nov 11, 2018 PDT
            [payment_status] => Completed
            [charset] => windows-1252

        )

)

我试图这样阅读:

<?php
$orders=file_get_contents("orders.log");
echo $orders['time'];
echo $myarray[0]['gateway'];
echo $myarray[1]['mc_gross']; 
?>

但是结果不能按预期工作。它抛出“ A”和“ r”。任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:1)

假设每个条目的长度为20行,它将读取日志文件,并使用array_chunk()将其分成20个段。

然后处理每个段,首先使用=>通过explode()分割线,然后将值添加到以左手边为键的关联数组中。然后,您可以使用该键访问每个值。

$input = file("log.txt", FILE_IGNORE_NEW_LINES);

$orders = array_chunk($input, 20);
foreach ( $orders as $order )   {
    $split = [];
    foreach ( $order as $line ) {
        $info = explode("=>", $line);
        if ( count($info) == 2){
            $split[trim($info[0]," \t[]")] = trim ($info[1]);
        }
    }

    echo "gateway-".$split['gateway'].PHP_EOL;
    echo "mc_gross-".$split['mc_gross'].PHP_EOL;
}

如果您想要所有订单的清单...

$input = file("log.txt", FILE_IGNORE_NEW_LINES);

$orders = array_chunk($input, 20);
$orderList = [];
foreach ( $orders as $order )   {
    $split = [];
    foreach ( $order as $line ) {
        $info = explode("=>", $line);
        if ( count($info) == 2){
            $split[trim($info[0]," \t[]")] = trim ($info[1]);
        }
    }
    $orderList[] = $split;
}


echo "gateway-".$orderList[0]['gateway'].PHP_EOL;
echo "mc_gross-".$orderList[0]['mc_gross'].PHP_EOL;

第三种方法,它不依赖于数据完全相同的格式,它逐行读取并尝试计算出元素本身的末尾(仅包含)的行) ...

$fp = fopen("log.txt", "r");
$orderList = [];
$order = [];
while ( $line = fgets($fp)) {
    // Remove extra data after content
    $line = rtrim($line);
    // If end of order (a line just starting with a ')')
    if ( $line == ')' ) {
        // Convert order into associative array
        $split = [];
        foreach ( $order as $line ) {
            $info = explode("=>", $line);
            if ( count($info) == 2){
                $split[trim($info[0]," \t[]")] = trim ($info[1]);
            }
        }
        // Add data to order list
        $orderList[] = $split;
        $order = [];
    }
    else {
        // Add line to existing data
        $order[] = $line;
    }
}

print_r($orderList);
fclose($fp);