我很难找到一个好的解决方案或之前的问题,因为它难以用语言表达,但我在这里有一个json对象:
{
"type":"template",
"customStyle":false,
"preheaderVisible":true,
"titleText":"Email Template",
"mainBlocks":{
"type":"blocks",
"blocks":[
{
"type":"singleArticleBlock",
"image":{
"type":"image",
"src":"/template/image/logo-large.png",
"url":"http://example.com/",
"alt":""
},
"longText":"\n <p>Far far away, behind the word mountains, far from the countries <a href=\"\">Vokalia and Consonantia</a>, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean. A small river named Duden flows by their place and supplies it with the necessary regelialia.</p>\n ",
"buttonLink":{
"type":"link",
"text":"BUTTON",
"url":"http://example.com/"
}
},
{
"type":"tripleArticleBlock",
"leftImage":{
"type":"image",
"src":"/template/image/logo-small.png",
"url":"http://example.com/",
"alt":""
},
"leftLongText":"\n <p>Far far away, behind the word mountains, far from the countries <a href=\"\">Vokalia and Consonantia</a>, there live the blind texts. </p>\n ",
"leftButtonLink":{
"type":"buttonLink",
"text":"BUTTON",
"url":"http://example.com/"
},
"middleImage":{
"type":"image",
"src":"/template/image/logo-small.png",
"url":"http://example.com/",
"alt":""
},
"middleLongText":"\n <p>Far far away, behind the word mountains, far from the countries <a href=\"\">Vokalia and Consonantia</a>, there live the blind texts. </p>\n ",
"middleButtonLink":{
"type":"buttonLink",
"text":"BUTTON",
"url":"http://example.com/"
},
"rightImage":{
"type":"image",
"src":"",
"url":"http://example.com/",
"alt":""
},
"rightLongText":"\n <p>Far far away, behind the word mountains, far from the countries <a href=\"\">Vokalia and Consonantia</a>, there live the blind texts. </p>\n ",
"rightButtonLink":{
"type":"buttonLink",
"text":"BUTTON",
"url":"http://example.com/"
}
},
]
}
}
我需要获取每个url
属性,无论它的嵌套深度或子对象如何。因此它可能是image
或leftButtonLink
的网址并在任何深度。我认为那里必须是一个简单的&#34;给我所有的道具叫做x&#34;功能。什么是在php中最有效的方法?
答案 0 :(得分:1)
这是未经测试的,尝试这样的事情
$data = json_decode($jsondata, true);
$urls = array();
r_search($data);
function r_search($array) {
global $urls;
foreach ($array as $key => $value) {
if (is_array($value)) {
r_search($value);
} else if ($key === 'url') {
$urls[] = $value;
}
}
}
没有全局变量可能还有更好的方法。做一些搜索递归数组搜索。
答案 1 :(得分:1)
array_walk_recursive
应该可以很好地解决这个问题。
$data = json_decode($json, true);
$urls = [];
array_walk_recursive($data, function($value, $key) use (&$urls) {
if ($key == 'url') $urls[] = $value;
});
确保通过设置json_decode
的第二个参数来解码到数组而不是对象。
但是,如果重要的话,这不会告诉您 的URL是什么。 (例如image
,leftButtonLink
等等。这只是一个简单的#34;给我所有的道具叫x&#34;功能