通过乘以两个键值对多维关联数组进行排序

时间:2018-06-04 09:47:19

标签: php sorting multidimensional-array

我有一个如下所示的数组:

$myarray = array(
   array('itemid' => '1','height'=>'5','length' => '5'),//area=25(height*length)
   array('itemid' => '2','height'=>'2','length' => '5'),//area=10(height*length)
   array('itemid' => '3','height'=>'5','length' => '3'),//area=15(height*length) 
  );

我想按升序对它进行排序,方法是通过乘以每个数组项的高度和长度(字符串值)来计算面积,如下所示

$sortedarray = array(
   array('itemid' => '2','height'=>'2','length' => '5'),//area=10(height*length)
   array('itemid' => '3','height'=>'5','length' => '3'),//area=15(height*length)
   array('itemid' => '1','height'=>'5','length' => '5'),//area=25(height*length)
);

我知道php有array_multisort功能,但我需要通过计算区域进行排序。

1 个答案:

答案 0 :(得分:5)

您可以使用componentDidMount() { restClient("GET_ONE", 'customers', {pagination: { page: 1, perPage: 5 }, sort: { field: 'name', order: 'ASC' }, id: 5}) .then(response => { this.setState({customerData: response.data}); } }); } render() { const FormToolbar = props => <Toolbar> <SaveButton label="Save" /> </Toolbar>; return ( <Card> <ViewTitle title="Edit customer" /> <SimpleForm record={this.state.customerData} toolbar={<FormToolbar />} > <TextInput source="name" /> <TextInput source="email" /> <TextInput source="street" /> <TextInput source="postal_code" /> <TextInput source="city" /> </SimpleForm> </Card> ); }

如果usort是第一个,

Usort回调函数需要-1(负数)。如果$a应该先行,则为1(正数);如果订单没有变更,则为$b

实施例: 0的区域为25,$a为10. $b,这是一个正数。因此25-10 = 15会在usort

之前订购$b
$a

这将导致:

$myarray = array(
    array('itemid' => '1','height'=>'5','length' => '5'),//area=25
    array('itemid' => '2','height'=>'2','length' => '5'),//area=10
    array('itemid' => '3','height'=>'5','length' => '3'),//area=15 
);

usort( $myarray, function($a, $b){
    return ( $a['height'] * $a['length'] )  - ( $b['height'] * $b['length'] );
});

echo "<pre>";
print_r( $myarray );
echo "</pre>";

Doc:usort()