我有一个像这样的数组
array(2) {
[0]=> object(stdClass)#20
(4) {
["id"]=> string(1) "1"
["name"]=> string(6) "robert"
["height"]=> string(3) "165"
["weight"]=> string(2) "81" }
[1]=> object(stdClass)#21
(4) {
["id"]=> string(1) "2"
["name"]=> string(4) "mike"
["height"]=> string(3) "175"
["weight"]=> string(2) "69" } }
所以,我想改变我的数组值。
例如,我想要更改["height"]
和["weight"]
的所有值。我以这样的数字形式对身高和体重进行分类:
height
1
= 150
.......... 170
2
= 171
.......... 190
weight
1
= 50
........... 70
2
= 71
........... 80
array(2) {
[0]=> object(stdClass)#20
(4) {
["id"]=> string(1) "1"
["name"]=> string(6) "robert"
["height"]=> string(1) "1"
["weight"]=> string(1) "2" }
[1]=> object(stdClass)#21
(4) {
["id"]=> string(1) "2"
["name"]=> string(4) "mike"
["height"]=> string(1) "2"
["weight"]=> string(1) "1" } }
我的数组是dynamic
,因此值可以随时更改。当然["name"]
根本不会改变,因为我没有给出分类。你能帮我解决这个问题吗?
答案 0 :(得分:2)
给出你的示例数组:
//example people array
$people = [
//robert
(object)[
"id" =>"1",
"name"=> "robert",
"height" => "165",
"weight" => "79",
],
//mike
(object)[
"id" => "2",
"name"=> "mike",
"height"=> "175",
"weight" =>"69",
]
];
您可以在稍微比较之后遍历数组并修改每个对象。注意我没有检查所有可能的范围以保持这种简洁(它应该只是几个检查)
//walk the array
array_walk($people, function($person){
//test height and assign category
if($person->height <= 190 && $person->height > 170)
$person->height = "2";
else
$person->height = "1";
//test weight and assign category
if($person->weight <= 80 && $person->weight > 70)
$person->weight = "2";
else
$person->weight = "1";
});
产生所需的结果,你可以检查实时here(CTRL + ENTER运行)
答案 1 :(得分:1)
您可以使用像array_map
function changeMe($itemArr) {
foreach($itemArr as $key=>$value) {
if($key == "a") {
$itemArr[$key] = "newVal";
}
}
return $itemArr;
}
$myArray = array(
0=>array(
"a"=>"1",
"b"=>"2"
),
1=>array(
"a"=>"1",
"b"=>"44"
)
);
$myArray = array_map("changeMe", $myArray);
var_dump($myArray);
答案 2 :(得分:1)
如果要更改当前数组,请使用array_walk()
如果要生成新数组,请使用array_filter()
请注意,除非您执行任何查询,否则它们中的任何一个都不会更改数据库中的值。
使用array_walk()
,
$array = array(); // your input array here
array_walk( $array, function(&$v){
( $v->height > 149 && $v->height < 171 ) ? ( $v->height = 1 ) : ( $v->height = 2 );
( $v->weight > 49 && $v->weight < 71 ) ? ( $v->weight = 1 ) : ( $v->weight = 2 );
});
使用array_filter()
,
$array = array(); // your input array here
$your_new_array = array_filter( $array, function($v){
( $v->height > 149 && $v->height < 171 ) ? ( $v->height = 1 ) : ( $v->height = 2 );
( $v->weight > 49 && $v->weight < 71 ) ? ( $v->weight = 1 ) : ( $v->weight = 2 );
return true;
});