这段时间做数据统计,产品那边要求数据能按高到低排序,想了很多方法,都不行。最后找到PHP的array_multisort()方法。虽然实现了效果,但对这个方法还是半董半董 下边就是使用的实例,手册上的例子不列了,就我自己工作中的几个。 工作中碰到最多的可能就是
这段时间做数据统计,产品那边要求数据能按高到低排序,想了很多方法,都不行。最后找到PHP的array_multisort()方法。虽然实现了效果,但对这个方法还是半董半董
下边就是使用的实例,手册上的例子不列了,就我自己工作中的几个。
工作中碰到最多的可能就是二维数组了,想试试三维数组,但是想想还是算了。
如果有误,请以PHP官网的官方手册为准。http://php.net/manual/zh/function.array-multisort.php
<span> 1</span> <span>header</span>('Content-Type: text/html; charset=utf-8'<span>); </span><span> 2</span> <span>echo</span> '<pre class="brush:php;toolbar:false">'<span>; </span><span> 3</span> <span>//</span><span>原始数组格式</span> <span> 4</span> <span>$array</span> = <span>array</span><span>( </span><span> 5</span> 'key1' => <span>array</span><span>( </span><span> 6</span> 'item1' => '65', <span> 7</span> 'item2' => '35', <span> 8</span> 'item3' => '84', <span> 9</span> ), <span>10</span> 'key2' => <span>array</span><span>( </span><span>11</span> 'item1' => '24', <span>12</span> ), <span>13</span> 'key3' => <span>array</span><span>( </span><span>14</span> 'item1' => '38', <span>15</span> 'item3' => '45', <span>16</span> ), <span>17</span> <span>); </span><span>18</span> <span>//</span><span>要排序的键 </span><span>19</span> <span>//按照数组中的 item1进行排序 </span><span>20</span> <span>//你也可以换成item2</span> <span>21</span> <span>$sort</span> = 'item1'<span>; </span><span>22</span> <span>foreach</span>(<span>$array</span> <span>as</span> <span>$k</span> => <span>$v</span><span>) </span><span>23</span> <span>{ </span><span>24</span> <span>$newArr</span>[<span>$k</span>] = <span>$v</span>[<span>$sort</span><span>]; </span><span>25</span> <span>} </span><span>26</span> <span>//</span><span>这个函数如果执行正确他会直接改变原数组键值的顺序 </span><span>27</span> <span>//如果执行失败,那么他会返回 bool(false)</span> <span>28</span> <span>array_multisort</span>(<span>$newArr</span>,SORT_DESC, <span>$array</span><span>); </span><span>29</span> <span>var_dump</span>(<span>$array</span><span>); </span><span>30</span> <span>//</span><span>---------------------排序后的数组打印效果 开始--------------------</span> <span>31</span> <span>array</span>(3<span>) { </span><span>32</span> ["key1"]=> <span>33</span> <span>array</span>(3<span>) { </span><span>34</span> ["item1"]=> <span>35</span> <span>string</span>(2) "65" <span>36</span> ["item2"]=> <span>37</span> <span>string</span>(2) "35" <span>38</span> ["item3"]=> <span>39</span> <span>string</span>(2) "84" <span>40</span> <span> } </span><span>41</span> ["key3"]=> <span>42</span> <span>array</span>(2<span>) { </span><span>43</span> ["item1"]=> <span>44</span> <span>string</span>(2) "38" <span>45</span> ["item3"]=> <span>46</span> <span>string</span>(2) "45" <span>47</span> <span> } </span><span>48</span> ["key2"]=> <span>49</span> <span>array</span>(1<span>) { </span><span>50</span> ["item1"]=> <span>51</span> <span>string</span>(2) "24" <span>52</span> <span> } </span><span>53</span> <span>} </span><span>54</span> <span>//</span><span>---------------------排序后的数组打印效果 结束---------------------</span>