提问者:小点点

在PHP中使用foreach循环将数组值转换为单个数组


我正在使用php和数组,我有如下多个数组

Array
(
    [0] => Array
        (
            [wallet_address] => 0x127e61982701axxxxxxxxxxxxxxxxxxxxxxxxxxx
        )

    [1] => Array
        (
            [wallet_address] => 0xf80a41eE97e3xxxxxxxxxxxxxxxxxxxxxxxxxxxx
        )

    [2] => Array
        (
            [wallet_address] => 0x24361F1602bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        )

等等

我想用逗号将它们放在一个数组中,如下所示

$set = array("0x127e61982701axxxxxxxxxxxxxxxxxxxxxxxxxxx","0xf80a41eE97e3xxxxxxxxxxxxxxxxxxxxxxxxxxxx","0x24361F1602bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");

我怎么能这么做?这是我目前的代码,但不工作,显示我相同的结果(0,1,2键),我错在哪里?

$GetUserFollower; //contaning multiple array value
$set=array();
foreach($GetUserFollower as $arr)
{
    $set[]=$arr;
    
}

echo "<pre>";print_R($set);

共2个答案

匿名用户

原始数组是一个Assoc数组,因此钱包地址需要在循环中专门寻址。或者您可以使用array\u column()内置函数来实现同样的功能。

$GetUserFollower; //contaning multiple array value
$set=array();
foreach($GetUserFollower as $arr)
{
    $set[] = $arr['wallet_address'];
    
}

echo "<pre>";print_r($set);

$new = array_column($GetUserFollower, 'wallet_address');
print_r($new);

后果

Array
(
    [0] => 0x127e61982701axxxxxxxxxxxxxxxxxxxxxxxxxxx
    [1] => 0xf80a41eE97e3xxxxxxxxxxxxxxxxxxxxxxxxxxxx
    [2] => 0x24361F1602bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
)

你的评论让我觉得你想要一个没有键的数组,这是不可能的。如果您使用您在评论中显示的示例执行此操作

$set = array("0x127e61982701axxxxxxxxxxxxxxxxxxxxxxxxxxx","0xf80a41eE97e3xxxxxxxxxxxxxxxxxxxxxxxxxxxx","0x24361F1602bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
print_r($set);

你会看到的

Array
(
    [0] => 0x127e61982701axxxxxxxxxxxxxxxxxxxxxxxxxxx
    [1] => 0xf80a41eE97e3xxxxxxxxxxxxxxxxxxxxxxxxxxxx
    [2] => 0x24361F1602bxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
)

匿名用户

在Foreach循环中,添加[0]

$set[]=$arr[0];

请试一试