我有這樣的數(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ù)字分類:
高度
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ù)組是動態(tài)的,因此值可以隨時更改.當(dāng)然,[“ name”]不會改變,因為我沒有給出分類.您能幫我解決這個問題嗎?
解決方法:
給定您的示例數(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ù)組并修改每個對象.請注意,我不會檢查所有可能的范圍以保持簡潔(應(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";});
來源:https://www.icode9.com/content-1-529451.html
聯(lián)系客服