|
我有這樣的數(shù)組
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" } }
因此,我想更改數(shù)組值.
例如,我想更改[[height]]和[[weight]]的所有值.我將身高和體重按如下數(shù)字分類(lèi):
高度
1 = 150 ………. 170
2 = 171 ………. 190
重量
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" } }
我的數(shù)組是動(dòng)態(tài)的,因此值可以隨時(shí)更改.當(dāng)然,[“ name”]不會(huì)改變,因?yàn)槲覜](méi)有給出分類(lèi).您能幫我解決這個(gè)問(wèn)題嗎? 解決方法: 給定您的示例數(shù)組為:
//example people array
$people = [
//robert
(object)[
"id" =>"1",
"name"=> "robert",
"height" => "165",
"weight" => "79",
],
//mike
(object)[
"id" => "2",
"name"=> "mike",
"height"=> "175",
"weight" =>"69",
]
];
您可以在稍作比較之后遍歷數(shù)組并修改每個(gè)對(duì)象.請(qǐng)注意,我不會(huì)檢查所有可能的范圍以保持簡(jiǎn)潔(應(yīng)該再檢查幾下)
//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";
});
可以產(chǎn)生期望的結(jié)果,您可以實(shí)時(shí)檢查"1",
"name"=> "robert",
"height" => "165",
"weight" => "81",
],
//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";
});
print_r($people);" rel="nofollow">here=>=>(運(yùn)行CTRL ENTER) 來(lái)源:https://www./content-1-529451.html
|