将项目添加到php中索引0处的关联数组中

时间:2022-08-26 14:07:11
$result=mysql_query("SELECT * FROM users where id=1");
print_r($result);

Here is the result data from mysql query.

这是来自mysql查询的结果数据。

Array
(
    [0] => stdClass Object
        (
            [firstname] => "John"
            [middleinitial] => "A."
            [lastname] => "Doe"
        )
)

I want to add address: "USA" after the lastname that will result like this:

我想在最后一个名字后面加上地址:USA

Array
(
    [0] => stdClass Object
        (
            [firstname] => "John"
            [middleinitial] => "A."
            [lastname] => "Doe"
            [address] => "USA"
        )
)

How can I append that to $result variable in php? Help would much appreciated. Tnx :)

如何在php中附加到$result变量?帮助会感谢。Tnx:)

3 个解决方案

#1


2  

This will work in one/more than one element case

这将适用于一个/多个元素情况

$result = array_map(function ($v) {
    $v->address = "USA";
    return $v;
}, $result);

Give it a try. This should work.

试一试。这应该工作。

#2


1  

This will work

这将工作

  $result[0]->address = "USA";

#3


1  

You simply need to add a property to the object contained in the first index of your array,

只需向数组的第一个索引中包含的对象添加一个属性,

$result[0]->address = 'USA';

Furthermore, if your array has multiple indices and you want to iterate through them all and add an address then you can do the following:

此外,如果你的数组有多个索引,你想要遍历所有索引并添加一个地址,那么你可以这样做:

foreach ($result as &$row) {
    $row->address = 'USA';
}

where the & is to pass the $row variable into the loop by reference so that you can modify it.

其中&通过引用将$row变量传递到循环中,以便您可以修改它。

#1


2  

This will work in one/more than one element case

这将适用于一个/多个元素情况

$result = array_map(function ($v) {
    $v->address = "USA";
    return $v;
}, $result);

Give it a try. This should work.

试一试。这应该工作。

#2


1  

This will work

这将工作

  $result[0]->address = "USA";

#3


1  

You simply need to add a property to the object contained in the first index of your array,

只需向数组的第一个索引中包含的对象添加一个属性,

$result[0]->address = 'USA';

Furthermore, if your array has multiple indices and you want to iterate through them all and add an address then you can do the following:

此外,如果你的数组有多个索引,你想要遍历所有索引并添加一个地址,那么你可以这样做:

foreach ($result as &$row) {
    $row->address = 'USA';
}

where the & is to pass the $row variable into the loop by reference so that you can modify it.

其中&通过引用将$row变量传递到循环中,以便您可以修改它。