[英]Find value of specific key in multidimensional array
从json提要中,我收到一个多维数组,如下所示。 在这个数组中,我需要特定键的一些值,例如[payment_url]的值。 我知道我可以用
$arr['transactions'][0]['payment_url'];
但是由于文档有点“简洁”,所以我不确定是否会有额外的答复。
Henche,我想要一个函数,该函数提供键名并返回与键处于哪个级别无关的值。 就像是
getValue($arr, 'payment_url');
我该怎么做呢?
Array
(
[amount] => 2525
[client] => Array
(
[user_agent] => gingerphplib
)
[created] => 2016-01-15T21:35:17.032535+00:00
[currency] => EUR
[description] => this is a description
[flags] => Array
(
[0] => is-test
)
[id] => xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
[merchant_order_id] => 205
[modified] => 2016-01-15T21:35:17.734427+00:00
[project_id] => xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
[return_url] => http://path/to/return/url/test
[status] => new
[transactions] => Array
(
[0] => Array
(
[amount] => 2525
[balance] => test
[created] => 2016-01-15T21:35:17.231677+00:00
[currency] => EUR
[description] => dit is een omschrijving met een enter
[id] => xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
[modified] => 2016-01-15T21:35:17.612664+00:00
[payment_method] => ideal
[payment_method_details] => Array
(
[issuer_id] => INGBNL2A
)
[payment_url] => https://link/to/payment/
[status] => new
)
)
)
从纯粹的技术角度来看,您可以执行以下操作
<?php
$response = json_decode(data(), true);
$flat = flatten($response);
echo $flat['payment_url'], ' | ', $flat['issuer_id'];
function flatten(array $arr) {
$rii = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr), RecursiveIteratorIterator::LEAVES_ONLY );
foreach( $rii as $k=>$v) {
$rv[$k] = $v;
}
return $rv;
}
function data() {
return <<< eoj
[
{
"id": "1dc05e5f-c455-4f06-bc9f-37a2db3a75e1",
"created": "2014-07-14T10:13:50.726519+00:00",
"modified": "2014-07-14T10:13:51.593830+00:00",
"merchant_order_id": "EXAMPLE001",
"status": "new",
"type": "payment",
"amount": 995,
"currency": "EUR",
"description": "Example order #1",
"return_url": "http://www.example.com/",
"transactions": [
{
"id": "90b70bba-e298-4687-a2f2-095f7ebc9392",
"created": "2014-07-14T10:13:51.082946+00:00",
"modified": "2014-07-14T10:13:51.210838+00:00",
"status": "new",
"currency": "EUR",
"amount": 995,
"description": "Example order #1",
"expiration_period": "P30D",
"balance": "internal",
"payment_method": "ideal",
"payment_method_details": {
"issuer_id": "INGBNL2A"
},
"payment_url": "https://api.gingerpayments.com/redirect/90b70bba-e298-4687-a2f2-095f7ebc9392/to/payment/"
}
]
}
]
eoj;
}
看到http://docs.php.net/RecursiveIteratorIterator , http://docs.php.net/RecursiveArrayIterator
但我
宁愿
关于使用像这样的问题,给出的理由很可疑。 我建议你查“问题”进一步不要用这个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.