0

I have below array and i am trying to convert to string separated with comma.

$users_array = Array
(
[0] => Array
    (
        [0] => Array
            (
                [user_id] => 1
            )

        [1] => Array
            (
                [user_id] => 5
            )

    )

[1] => Array
    (
        [0] => Array
            (
                [user_id] => 6
            )

        [1] => Array
            (
                [user_id] => 13
            )

    )

)

Then i tried to convert in string with foreach

for($i = 0; $i < count($users_array); $i++){
    $xyz[] = implode(",",$users_array[$i]);
}
$users = implode(',',$xyz);

But it throw error Message: Array to string conversion

How can i convert it to string like 1,5,6,13?

Thank you,

3 Answers 3

1
for($i = 0; $i < count($users_array); $i++){
   for($j = 0; $j < count($users_array[$i]; $j++)) {
       $xyz[] = $users_array[$i][$j]["user_id"];
    }
}
$users = implode(',',$xyz);
Sign up to request clarification or add additional context in comments.

Comments

0
$user_ids = array();
foreach($users_array as $val){
    foreach($val as $v)){
       array_push($user_ids,$v['user_id']);
    }
} 
$users = implode(',',$user_ids);

This code is very easy and also use for as per your requirement.

Comments

0

hey @rjcode in php if you want to convert an array to comma separated string so use function implode(separation letter, $array) and for vice versa means string to an array so use function explode(separation letter, string)

for your case use use implode() so for your code try below one

 <?php
    for($i = 0; $i < count($users_array); $i++){
   for($j = 0; $j < count($users_array[$i]; $j++)) {
       $xyz[] = $users_array[$i][$j]["user_id"];
    }
    }
    $users = implode(',',$xyz);
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.