简体   繁体   中英

Create array dynamically in Foreach loop

I am trying create an array in a foreach loop, and then sort it by a key.

The for each loop creating the array looks like this:

public function index(){

    $query=$this->My_model->get_data();
    foreach ($query as $row)
    {
           $data=array(
           Array('Points'=>$points,'Name'=>$row['Name'], 'Phone'=>$row['phone']),
            );

           function cmp ($a, $b) {
        return $a['Points'] < $b['Points'] ? 1 : -1;
        }

        usort($data, "cmp");

        print_r($data);


        }
    }

But this only returns the first the first item in the array.

However when I input some array items directly such as the below, it works fine and sorts all the array items.

public function index(){

    $query=$this->My_model->get_data();
    foreach ($query as $row)
    {
         $data = array (
    Array ( 'Points' => 500, 'Name' => 'James Lion' ) ,
    Array ( 'Points' => 1200, 'Name' => 'John Smith' ), 
    Array ( 'Points' => 700, 'Name' => 'Jason Smithsonian' ) );

           function cmp ($a, $b) {
        return $a['Points'] < $b['Points'] ? 1 : -1;
        }

        usort($data, "cmp");

        print_r($data);

        }
    }

How do I fix this so that the code in the first snippet, so that works as it does in the second snippet?

You have to change the code piece like this

$data[]=array('Points'=>$points,'Name'=>$row['Name'], 'Phone'=>$row['phone']));

The problem with your code is , you are not creating a multidimensional array and instead overwriting the $row values in $data which eventually has the last data since all the other data is overwritten

Also move your function cmp outside of the foreach loop

Have you tried using your custom sort on the outside, (after building your array on the loop). Consider this example:

public function index()
{
    $query = $this->My_model->get_data();
    foreach ($query as $row) {
        $data[] = array('Points' => $points,' Name' => $row['Name'], 'Phone' => $row['phone']),);
    }

    function cmp ($a, $b) {
        return $a['Points'] < $b['Points'] ? 1 : -1;
    }

    usort($data, "cmp");
    print_r($data);
}

Store your values into array format lock like this $data[]

foreach ($query as $row)
    {
           $data[]=array(
           Array('Points'=>$points,'Name'=>$row['Name'], 'Phone'=>$row['phone']),
            );
   }

Then you print the data outside of foreach loop

print_r($data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM