多维PHP数组

时间:2013-03-15 21:58:34

标签: php arrays json curl multidimensional-array

我无法找到一种编写PHP脚本的方法,该脚本将打印名字,姓氏,电子邮件和帐户ID 这个多维数组。这是从cURL脚本返回的json数据。你能帮助我的朋友吗?

Array
(
    [operationResult] => SUCCESS
    [responseDateTime] => 2013-03-15T15:52:25.180-05:00
    [page] => Array
        (
            [currentPage] => 1
            [pageSize] => 10
            [totalPage] => 1
            [totalResults] => 1
        )
    [searchResults] => Array
        (
            [nameValuePairs] => Array
                (
                    [nameValuePair] => Array
                        (
                            [0] => Array
                                (
                                    [name] => Account Id
                                    [value] => 7601
                                )

                            [1] => Array
                                (
                                    [name] => User Email 1
                                    [value] => jim@email.com
                                )

                            [2] => Array
                                (
                                    [name] => First Name
                                    [value] => Jim
                                )

                            [3] => Array
                                (
                                    [name] => Last Name
                                    [value] => Burns
                                )
                        )
                )
        )
)

修改:抱歉不包括我的尝试。我尝试过以下方法:

foreach ($client_emails_array as $operation) 
{ 
    echo $operation['page']['searchResults']['nameValuePairs']['nameValuePair']['name']."<br>";
    echo $operation['page']['searchResults']['nameValuePairs']['nameValuePair']['value']."<br>";
}

这让我没那么成功

3 个答案:

答案 0 :(得分:1)

对于您的用例,数据结构实际上很差,但您应该能够像这样:

$data_array = $main_array['searchResults']['nameValuePairs']['nameValuePair']
$final_array = array();
foreach($data_array as $nvp) {
    $final_array[$nvp['name']] = $nvp['value'];
}
var_dump ($final_array);

答案 1 :(得分:1)

严格来说,只需打印值即可:

foreach ($operation['searchResults']['nameValuePairs']['nameValuePair'] as $key => $data) {
    echo $data['value'];
}

如果您想要做更多,可以在foreach块中添加更多逻辑,以检索已打印的值等等。

答案 2 :(得分:1)

在您的修改中,['searchResults']不在['page']数组中。请尝试删除['page']

foreach ($client_emails_array as $operation) 
{ 
   echo $operation['searchResults']['nameValuePairs']['nameValuePair']['name']."<br>";
   echo $operation['searchResults']['nameValuePairs']['nameValuePair']['value']."<br>";
}