1

I have array like this:

array(
    [0] => Array
    (
        [q_id] => 314
        [answer_type] => RI
        [answer] => 3438
        [user_id] => 
    )

[1] => Array
    (
        [q_id] => 286
        [answer_type] => NM
        [answer] => 5
        [user_id] => 
    )

[2] => Array
    (
        [q_id] => 207
        [answer_type] => SS
        [answer] => 1
        [user_id] => 1
    )
 )

Its expected to have same user_id for all questions that have value for user_id or empty. I want to replace empty user_ids with the existing user_id.

Any better ways to do it other than looping / array_walk?

2 Answers 2

1

Don't think so.

$arr = array_map(function ($val) use ($user_id) {
    if (empty($val['user_id'])) {
        $val['user_id'] = $user_id;
    }

    return $val;
}, $arr);

I am of course assuming you have PHP 5.3+

Sign up to request clarification or add additional context in comments.

Comments

0

Anyhow you will need to loop. As it is not clear how big the array could be / how would the array be sorted, there are not many ways to assign the value without walking through them.

Thinking outside the box. Generally the array will be used somewhere in the script and there will be code to access the values inside the array. Is there any chance to assign the desired user_id to the output when you are accessing the array?

1 Comment

This array is resulting from the query. So I can't check the value of the user_id of the previous row. The array can be as big as 60 rows.

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.