繁体   English   中英

如何使用 PHP 更新或更改数组

[英]How can i update or change in array using PHP

我需要更新这个 JSON 的属性accessories

{
  id: "1",
  name: "TEST",
  accessories: [
        "1",
        "2",
        "3"
  ]
}

如何在accessories数组中添加4或将3更改为4

//Decode JSON to PHP object
$arrr = json_decode('{
  "id": "1",
  "name": "TEST",
  "accessories": [
        1,
        2,
        3
  ]
}');

$old_value  = 3;    // The value you want to change
$new_value1 = 4;    // The value you want to change it to
$new_value2 = 100;  // A new value you want to insert into the array

$array_key = array_search($old_value, $arrr->accessories);  // Get array key of old value
$arrr->accessories[$array_key] = $new_value1;               // Update array with value

$arrr->accessories[] = $new_value2;                         // Add extra value to array

echo json_encode($arrr);             // Re-encode and print results

// Output: {"id":"1","name":"TEST","accessories":[1,2,4,100]}

您可以使用array_map作为方法:

<?php
$json = json_decode('{
  "id": "1",
  "name": "TEST",
  "accessories": [
        1,
        2,
        3
  ]
}', true);

$json['accessories'] = array_map(
    function($el) {
        return $el == 3 ? 4 : $el;
    },
    
    $json['accessories']
);

print_r($json);

您可以在PHPize.online上测试解决方案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM