分享

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

 印度阿三17 2019-10-28

我有这样的数组

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

可以产生期望的结果,您可以实时检查"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(运行CTRL ENTER)

来源:https://www./content-1-529451.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多