Home > Net >  Array values to single array using foreach loop in PHP
Array values to single array using foreach loop in PHP

Time:12-20

I am working with php and arrays, I have multiple arrays like following

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

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

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

and so on....

And i want to make them in single array with comma like following way

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

How can i do this ?Here is my current code but not working,showing me same result(0,1,2 keys),Where i am wrong ?

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

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

CodePudding user response:

The original array is an Assoc array and therefore the wallet_address needs to be addressed specifically in a loop. Or you could use the array_column() builtin function to achieve the same thing.

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

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

Or

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

RESULT

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

Your comments are making me think you want an array without a key, which is impossible. If you do this with the example you show in your comments

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

You will see

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

CodePudding user response:

in your foreach loop , add [0]

$set[]=$arr[0];

please try

  • Related