[英]Inserting a key value pair after a certain key value in PHP
I am trying to insert a key value pair at the end of an array of values retrieved from a database query. 我试图在从数据库查询中检索到的值数组的末尾插入一个键值对。 I tried
array_splice
but that wasn't doing exactly what I wanted, so I'm trying array_push
but it's not adding it to the array. 我尝试了
array_splice
但是并没有完全按照我想要的去做,所以我在尝试array_push
但是没有将其添加到数组中。
Here is my code: 这是我的代码:
public function listFriendsStatus()
{
// get the friend statuses of the logged in user
$connection = $this->sql->getAdapter()->getDriver()->getConnection();
$query = $connection->execute("SELECT status.id, status, time_status, members.username FROM status
INNER JOIN friends ON friends.friend_id = status.id
INNER JOIN members ON members.id = status.id
WHERE friends.user_id = " . $this->getUserId()['id']);
if ($query->count() > 0) {
$status_holder = array();
foreach ($query as $key => $value) {
$status_holder[$key] = $value;
$status_dir = '/images/profile/' . $status_holder[$key]['username'] . '/status/' . $status_holder[$key]['time_status'] . '/';
$real_dir = getcwd() . '/public/' . $status_dir;
if (is_dir($real_dir)) {
$images = array_diff(scandir($real_dir, 1), array('.', '..'));
array_push($status_holder, array('images' => $images));
} else {
array_push($status_holder, array('images' => ''));
}
}
return $status_holder;
} else {
throw new FeedException("No friend statuses were found.");
}
}
For a better explanation, here is a var_export
of my array 为了更好的解释,这是我的数组的
var_export
array ( 0 => array ( 'id' => '2', 'status' => 'this is jimmy, test', 'time_status' => '0', 'username' => 'jimmy', ), 1 => array ( 'id' => '3', 'status' => 'this is jimmy 2, test', 'time_status' => '0', 'username' => 'timmy', ), 2 => array ( 'images' => '', ), )
What I am trying to do is insert after each ["username"]
key and value, the images key and value from the images array. 我想要做的是在每个
["username"]
键和值,图像数组中的图像键和值之后插入。
Any help would be appreciated. 任何帮助,将不胜感激。
Thanks! 谢谢!
(I can try and make the question clearer if need be) (如果需要,我可以尝试使问题更清楚)
update 更新
$status_holder[$key]['images'] = $images;
did what I need. 做了我需要的。
If your foreach is retrieving a row at a time, then add the image into this data and then build your other array... 如果您的foreach一次检索一行,则将图像添加到此数据中,然后构建另一个数组...
foreach ($query as $key => $value) {
$status_dir = '/images/profile/' . $value['username'] . '/status/' . $value['time_status'] . '/';
$real_dir = getcwd() . '/public/' . $status_dir;
if (is_dir($real_dir)) {
$images = array_diff(scandir($real_dir, 1), array('.', '..'));
$value['images'] = $images;
} else {
$value['images'] = '';
}
$status_holder[$key] = $value;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.