dongyikong6207 2012-02-28 22:53
浏览 137

php - 在循环时创建关联数组

I am trying to create 2 new arrays out of one existing array ($array), using the following "foreach" loop. However I am not sure it is correct:

        $emails = array();
        $numbers = array();
        while($array){
            $entry = $array['entry1'];
            $number = number($entry);
            if(isset($number) && (strlen($number) > 9)){
                $numbers[] = array('entry1' => $entry, 'number' => $number);
            }
            else{
                $email = email($entry);
                $emails[] = array('entry1' => $entry, 'email' => $email);
            }
        }

should the internal arrays have []? do I even need to start the arrays outside of the while loop? or skip it? is it better to use a foreach loop?

Update:

Okay, here is the original array: It is extracted from a mysql query, of sets of two numbers:

{('uid1','uid2'),('uid1','uid5'),('uid9','uid93'),....) There might be other data in each row, but these are the only two data points that really matter.

What I am trying to do is for a specific user ($entry), create two separate arrays: of all the users that have numbers (that's a function we have), and all the rest - of their emails. So the outcome will be 2 new arrays which will look like this: for a specific uid79887:

numbers array: {('uid8','xxx-xxxx-xxx'),('uid34','yyy-yyyy-yyy'),('uid654','vvv-vvvv-vvv')}

emails array: {('uid4','mmm@mmm.com'),('uid1','lll@lll.com'),('uid55554','ppp@ppp.com')}

  • 写回答

3条回答 默认 最新

  • duancan8382 2012-02-28 23:01
    关注

    Assuming this isn't some kind of homework assignment, why don't you do it this way:

    $emails = array();
    $numbers = array();
    
    foreach( $array as $entry )
    {
        $number = number($entry);
        if( $number && strlen($number) > 9 )
        {
            array_push($numbers, array('entry1' => $entry, 'number' => $number));
        }
        else
        {
            array_push($emails, array('entry1' => $entry, 'email' => email($entry)));
        }
    }
    

    It is better to use built in functions that trying to roll your own. The foreach() function works very well.

    评论

报告相同问题?