php数组函数array_push()、array_pop()、array_shift() 、array_unshift()简单用法示例:
<?php /** * array_push()将一个或多个单元压入数组的末尾(入栈) */ $stack = ['a', 'b']; array_push($stack, 'cc', 'dd', ['eee','fff']); var_dump($stack); //输出结果:['a','b','cc','dd',['eee','fff']] /** * array_pop() 将数组最后一个单元弹出(出栈) */ $stack = ['a', 'b', 'c']; array_pop($stack); var_dump($stack); //输出结果:['a','b'] /** * array_shift()将数组开头的单元移出数组 */ $stack = ['a', 'b','c']; array_shift($stack); var_dump($stack); //输出结果:['b', 'c']; /** * array_unshift()在数组开头插入一个或多个单元 */ $stack = ['a', 'b']; array_unshift($stack, 'cc', 'dd', ['eee','fff']); var_dump($stack); //输出结果:['cc','dd',['eee','fff'],'a','b']
demo示例: mysql查询二维多条数据(二维数组),需要根据某两字段比较大小,重新再排序
<?php $mysqlDatas = [ ['id' => 1, 'goods' => 'milk','totalPrice' => '9','balance' => '10'], ['id' => 2, 'goods' => 'apple','totalPrice' => '15','balance' => '10'], ['id' => 3, 'goods' => 'banana','totalPrice' => '5','balance' => '10'], ['id' => 4, 'goods' => 'orange','totalPrice' => '19','balance' => '10'], ]; $datas = []; foreach ($mysqlDatas as $data){ //总价大于余额数据排序最前面 if($data['totalPrice'] > $data['balance']){ array_unshift($datas, $data); }else{ array_push($datas, $data); } } var_dump($datas); //输出结果: // [ // ['id' => 4, 'goods' => 'orange','totalPrice' => '19','balance' => '10'], // ['id' => 2, 'goods' => 'apple','totalPrice' => '15','balance' => '10'], // ['id' => 1, 'goods' => 'milk','totalPrice' => '9','balance' => '10'], // ['id' => 3, 'goods' => 'banana','totalPrice' => '5','balance' => '10'], // ]