dqy012345 2013-06-15 20:30
浏览 25
已采纳

PHP按对象键排序数组数组[重复]

This question already has an answer here:

I have a form where I'm creating a number of item arrays:

<input type="hidden" value="Full/Double Mattress" name="pickup1-dropoff1Items[1][0]">
<input type="text" name="pickup1-dropoff1Items[1][1]">
<input type="hidden" value="20" name="pickup1-dropoff1Items[1][2]">
<input type="hidden" value="FMat" name="pickup1-dropoff1Items[1][3]">
<input type="hidden" value="1" name="pickup1-dropoff1Items[1][4]">

so the structure is basically:

array(
    array('title', quantity, price, 'shorthand', order),
    array('title', quantity, price, 'shorthand', order)
)

etc...

I'm getting this information using PHP and sending it in an email. I can get one of these arrays like so:

$pickup1_dropoff1Items = $_POST['pickup1-dropoff1Items'];

I would like to sort the arrays in $pickup1_dropoff1Items by the 'order' number (i.e. index #4, i.e. $pickup1-dropoff1Items[i][4]) in each of those arrays.

Can this be done using PHP ksort()? Does anyone have any idea how to sort an array like this using PHP?

Thanks!

</div>
  • 写回答

2条回答 默认 最新

  • dsaaqdz6223 2013-06-15 20:51
    关注

    It's not tested but I think this will do what you need:

    // first create a new array of just the order numbers 
    // in the same order as the original array
    $orders_index = array();
    foreach( $pickup1_dropoff1Items as $item ) {
      $orders_index[] = $item[4];
    }
    
    // then use a sort of the orders array to sort the original
    // array at the same time (without needing to look at the 
    // contents of the original)
    array_multisort( $orders_index, $pickup1_dropoff1Items );
    

    This is essentially example 1 here: http://www.php.net/manual/en/function.array-multisort.php but our $ar2 is an array of arrays instead of an array of single values. Also if you need more control over the sort you'll see examples of options you can use at that URL: just add them to the list of arguments for array_multisort.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?