以我的形式,im输出一些json或来自输入的数组的一串数据::old(‘tag’)我遇到的问题是能够测试它并查看它是否是json,如果它是json循环,并将tag属性放入数组,然后将数组内爆并输出到输入字段中。
[{"id":112,"tag":"corrupti","tagFriendly":"corrupti","created_at":"2015-07-20 00:05:28","updated_at":"2015-07-20 00:05:28","pivot":{"question_id":60,"tag_id":112,"created_at":"2015-07-20 00:05:28","updated_at":"2015-07-20 00:05:28"}},{"id":9,"tag":"placeat","tagFriendly":"placeat","created_at":"2015-07-20 00:05:23","updated_at":"2015-07-20 00:05:23","pivot":{"question_id":60,"tag_id":9,"created_at":"2015-07-20 00:05:28","updated_at":"2015-07-20 00:05:28"}}]所以我的输出应该如下所示
'corrupti, placeat, etc...'有人能帮我按照我刚才概述的步骤得到预期的结果吗?
这段代码不起作用,但这是我想要实现的。is_array总是错误的
<?php
$tags = Input::old('tags');
if(is_array($tags)) {
foreach ($tags as $tag) {
$tags[] = $tag->tag;
}
$tags = implode(', ', $tags);
}
?>发布于 2015-07-23 04:17:31
这就是你要的。
$tags = json_decode(Input::old('tags'), true); // decode json input as an array
if (is_array($tags)) {
foreach ($tags as $key=>$value) {
$tags[$key] = $value['tag'];
}
$tags = implode(', ', $tags);
echo $tags;
}发布于 2015-07-23 02:08:19
可以使用array_map从对象中提取标记属性。
<?php
$jsonObject = json_decode(Input::old('tags'));
if(is_array($jsonObject)) {
$onlyTags = array_map(function($item) { return $item->tag; },$jsonObject);
print implode(",", $onlyTags);
}发布于 2015-07-23 02:12:25
尝试将true添加到json_decode中。
json_decode($tags, true);根据应该返回关联数组的文档。http://php.net/manual/en/function.json-decode.php
is_array可能无法处理具有键/值对的关联数组。尝试用以下函数替换is_array:
function is_associate_array($array)
{
return $array === array_values($array);
}所以:
if(is_associate_array(json_decode($tags, true))) {
}https://stackoverflow.com/questions/31576968
复制相似问题