简体   繁体   English

在Foreach循环中动态创建数组

[英]Create array dynamically in Foreach loop

I am trying create an array in a foreach loop, and then sort it by a key. 我正在尝试在foreach循环中创建一个数组,然后按键对其进行排序。

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 您的代码存在的问题是,您不是在创建多维数组,而是覆盖$data$row值,由于所有其他数据均被覆盖,最终它具有最后一个数据

Also move your function cmp outside of the foreach loop cmp函数cmp移动到foreach循环之外

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[] 将值存储到数组格式锁中,例如$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 然后在foreach循环外打印数据

print_r($data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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