PHP-Codeigniter:如何从指定索引转换数组值?

我有这样的数组

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]]的所有值.我将身高和体重按如下数字分类

高度

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" } }

我的数组是动态的,因此值可以随时更改.当然,[“ name”]不会改变,因为我没有给出分类.您能帮我解决这个问题吗?

解决方法:

给定您的示例数组为:

//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)

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...