在PHP中的某个键值之后插入键值对

时间:2018-03-26 12:40:09

标签: php

我正在尝试在从数据库查询中检索的值数组的末尾插入键值对。我尝试了array_splice,但这并不是我想要的,所以我正在尝试array_push,但它没有将它添加到数组中。

这是我的代码:

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.");
    }
}

为了更好的解释,这里是我的数组的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' => '', ), )

我要做的是在每个["username"]键和值之后插入,图像键和图像数组中的值。

任何帮助都将不胜感激。

谢谢!

(如果需要,我可以尝试让问题更清晰)

更新

$status_holder[$key]['images'] = $images;

做了我需要的。

1 个答案:

答案 0 :(得分:3)

如果您的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;
}