如何使用php打印数组值

时间:2015-03-04 19:58:01

标签: php

我有一个从API填充数据的数组,我可以打印数组的值但是我无法打印数组中的选定字段。这是我可以打印整个数组的代码片段......

if($apiResponse['response']['status'] === 1) {
        // No errors encountered
        echo 'API call successful';
        echo PHP_EOL;

        echo print_r($apiResponse['response']['data'], true);

        echo PHP_EOL;
    }
    else {
        // An error occurred
        echo 'API call failed (' . $apiResponse['response']['errorMessage'] . ')';
        echo PHP_EOL;
        echo 'Errors: ' . print_r($apiResponse['response']['errors'], true);
        echo PHP_EOL;
    }

这里$ apiResponse ['response'] ['data']是包含以下值的数组...我想从数组中获取[name],[offer_url]和[preview_url]值...这是我能打印的数组......

( [3228] => Array ( [OfferUrl] => Array ( [id] => 3228 [offer_id] => 232 
[name] => larl [offer_url] => http://www.nsssa.com/brands/loreacdl-paris.html/?utm_source=abcd&utm_medium=Affiliates [preview_url] => http://www.nsssa.com/brands/larl-paris.html/?utm_source=abcd&utm_medium=Affiliates 
[status] => active [created] => 2014-10-23 03:15:29 [modified] => 0000-00-00 00:00:00 ) ) 
[3230] => Array ( [OfferUrl] => Array ( [id] => 3230 [offer_id] => 232 
[name] => Schwarzkopf [offer_url] => http://www.nsssa.com/brands/schwarzkopf.html/?utm_source=abcd&utm_medium=Affiliates [preview_url] => http://www.nsssa.com/brands/schwarzkopf.html/?utm_source=abcd&utm_medium=Affiliates 
[status] => active [created] => 2014-10-23 03:16:48 
[modified] => 0000-00-00 00:00:00 ) )

任何人都可以帮助我。

3 个答案:

答案 0 :(得分:0)

dont use print_r and echo in same lines

if($apiResponse['response']['status'] === 1) {
    // No errors encountered
    echo 'API call successful';
    echo PHP_EOL;

    echo $apiResponse['response']['data']['OfferUrl']['name'];

    echo PHP_EOL;
}
else {
    // An error occurred
    echo 'API call failed (' . $apiResponse['response']['errorMessage'] . ')';
    echo PHP_EOL;
    echo 'Errors: ' . $apiResponse['response']['errors'];
    echo PHP_EOL;
}

答案 1 :(得分:0)

只需访问数组键。

$id = $apiResponse['response']['data']['OfferUrl']['id'];
echo "id: $id\n";
$offer_id = $apiResponse['response']['data']['OfferUrl']['offer_id'];
$name = $apiResponse['response']['data']['OfferUrl']['name'];
.
.
.

答案 2 :(得分:0)

你的意思是这个吗?

echo 'Name: ' . $apiResponse['response']['data'][3228]['OfferUrl']['name'] . PHP_EOL;

或者

foreach ($apiResponse['response']['data'] as $data) {
    echo $data['OfferUrl']['name'] . PHP_EOL;
    // etc
}