我有一个数组:
Array
(
[0] => Array
(
[tree_level] => 1
[id] => 1
[products_id] => 13
[categories_id] => 1
)
[1] => Array
(
[tree_level] => 2
[id] => 2
[products_id] => 13
[categories_id] => 2
)
[2] => Array
(
[tree_level] => 3
[id] => 3
[products_id] => 13
[categories_id] => 3
)
[3] => Array
(
[tree_level] => 1
[id] => 1
[products_id] => 25
[categories_id] => 1
)
[4] => Array
(
[tree_level] => 2
[id] => 2
[products_id] => 25
[categories_id] => 2
)
)
是可能的选择max tree_level的每组具有相同的products_id。
结果应该像
For products_id = 13 max tree_level = 3对于products_id = 25 Max tree_level = 2
因为您没有提供任何代码,所以我只提供了我的一些代码;)
填空:
Mariusz: I fill the gaps
$aMaxCats = array(
array (
"tree_level" => 1,
"id" => 1,
"products_id" => 13,
"categories_id" => 1,
),
array (
"tree_level" => 2,
"id" => 2,
"products_id" => 13,
"categories_id" => 2,
),
array(
"tree_level" => 3,
"id" => 3,
"products_id" => 13,
"categories_id" => 3,
),
array (
"tree_level" => 1,
"id" => 1,
"products_id" => 25,
"categories_id" => 1,
),
array (
"tree_level" => 2,
"id" => 2,
"products_id" => 25,
"categories_id" => 2,
)
);
$newArray = array();
foreach( $aMaxCats as $product ) {
if( !isset( $product[ $product["products_id"] ] ) ) {
$newArray[ $product["products_id"] ] = array(
"product_id" =>$product["products_id"],
"categories_id"=>$product["categories_id"],
"max_tree_level" =>$product["tree_level"]
);
} else {
if( $newArray[$product["products_id"] ]["max_tree_level"] < $product["tree_level"] ) {
$newArray[$product["products_id"] ]["max_tree_level"] = $product["tree_level"];
}
}
}
// re-index array
$newArray = ___________ // google search for php reindex array
echo "<pre>";
var_dump( $newArray );
可以分组并选择max
<?php
$aMaxCats = array(
array (
"tree_level" => 1,
"id" => 1,
"products_id" => 13,
"categories_id" => 1,
),
array (
"tree_level" => 2,
"id" => 2,
"products_id" => 13,
"categories_id" => 2,
),
array(
"tree_level" => 3,
"id" => 3,
"products_id" => 13,
"categories_id" => 3,
),
array (
"tree_level" => 1,
"id" => 1,
"products_id" => 25,
"categories_id" => 1,
),
array (
"tree_level" => 2,
"id" => 2,
"products_id" => 25,
"categories_id" => 2,
)
);
foreach( $aMaxCats as $product ) {
$comapy[] = $product['products_id'];
$price[] = $product['tree_level'];
}
$group = array();
foreach($comapy as $key=>$val){
$group[$val][] = $price[$key];
}
// this loop for check the max number and count total price
$data = array();
$total = 0;
foreach($group as $key=>$val){
$data[][$key] = $key."-".current($val);
$data[][$key] = $key."-".max($val)." Max : ".max($val);
$total +=max($val);
}
// this foreach to convert your data to string
$result = "";
foreach($data as $key){
$result .= "'n".current($key);
}
// and show your data like string
print_r($result);
?>
比如data
$tmp=0;
foreach($arr as $key=>$value){
foreach($value as $k=>$data){
if($k=="categories_id"){
if($tmp<$data){
$tmp=$data;
}
}
}
}
echo $tmp;
Try max()
function
echo(max(tree_level" => 1,"id" => 1, "products_id" => 25,"categories_id" => 1,) . "<br>");
如echo (max(1,2,3));
结果为3