[英]Format the json encode just like on laravel php
Supposed I have a query that gets the image from a certain tweet 假设我有一个查询,该查询从某条推文获取图像
[
{
"pic": "/upload/15680712995mb.jpg",
"tweet_id": "48"
},
{
"pic": "/upload/1568071299test.PNG",
"tweet_id": "48"
},
{
"pic": "/upload/1568015310test.PNG",
"tweet_id": "47"
}
]
And I have a result also from a query that gets all of the tweet 我也从查询中获得了所有推文的结果
[
{
"id": "48",
"tweet": "test",
},
{
"id": "47",
"tweet": "test tweet",
},
{
"id": "45",
"tweet": "test tweet 3",
}
]
How can I format the result like this (Just like on laravel) 我该如何格式化结果(就像在laravel上一样)
[
{
"id": "48",
"tweet": "test",
"pics": [
[
"/upload/15680712995mb.jpg"
],
[
"/upload/1568071299test.PNG"
],
]
},
{
"id": "47",
"tweet": "test tweet",
"pics" : [
[
"/upload/1568015310test.PNG"
]
]
},
{
"id": "45",
"tweet": "test tweet 3",
"pics" : []
}
]
And this is my simplified code 这是我的简化代码
public function getTweets()
{
$pics = $this->model->getPics();
$aTweets = $this->model->getTweets();
$map = [];
$props = [];
foreach ($aTweets as $sTweet) {
$map['id'] = $sTweet['id'];
$map['tweet'] = $sTweet['tweet'];
foreach ($pics as $pic) {
if ($pic['id'] === $sTweet['tweet_id']) {
$map['pics'] = [$pic['pic']];
}
}
$props[] = $map;
}
return $props;
}
but it just gives me the following output 但这只是给我以下输出
{
"id": "48",
"tweet": "test",
"pics": [
"/upload/1568015310test.PNG"
]
},
{
"id": "47",
"tweet": "test tweet",
"pics": [
"/upload/1568015310test.PNG"
]
},
Any idea how can I format the result. 知道如何格式化结果。 thanks in advance.?
提前致谢。?
I'm not sure what's troubling you but in order to add multiple values inside, just put another nesting like what I've eluded in the comments section: 我不确定是什么困扰着您,但是为了在其中添加多个值,只需像在注释部分中所讲的那样放置另一个嵌套即可:
$map['pics'][] = $pic['pic'];
// ^
So to complete the answer: 因此要完成答案:
$map = [];
$props = [];
foreach ($aTweets as $sTweet) {
$map['id'] = $sTweet['id'];
$map['tweet'] = $sTweet['tweet'];
$map['pics'] = []; // initialize
foreach ($pics as $pic) {
if ($pic['tweet_id'] === $sTweet['id']) {
$map['pics'][] = [$pic['pic']];
}
}
$props[] = $map;
}
This essentially creates another dimension for pics
index as an array and continually pushing, provided they have the same ID. 本质上,这为
pics
索引创建了另一个维,作为数组并不断推送,只要它们具有相同的ID。
Sidenote: tweet_id
is to pics and id
is to aTweets . 旁注:
tweet_id
用于图片,而id
用于aTweets 。 Your's have the other way around. 您有另一种方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.