I need to update the property accessories of this JSON
{
id: "1",
name: "TEST",
accessories: [
"1",
"2",
"3"
]
}
How can I add 4 or change 3 to 4 to the accessories array?
//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]}
You can use array_map as approach:
<?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);
You can test the solution on PHPize.online
Related
I have the following JSON array, I would like to adjust the array to only keep unique name values, meaning id could be across numerous objects, but name must be unique, overall Tim and Jacob can only be listed once.
$data = '
[
{
"name": "Jacob",
"id": 4
},
{
"name": "Jacob",
"id": 3
},
{
"name": "Tim",
"id": 2
},
{
"name": "Brady",
"id": 2
},
{
"name": "Tim",
"id": 1
}
]';
$array = json_decode($data, TRUE);
$array = array_values( array_unique( $array, SORT_REGULAR ) );
$result = json_encode( $array );
The following is what I have currently tried, but it looks at both values in the object, so it leaves them as is.
Result I am looking for:
[
{
"name": "Jacob",
"id": 4
},
{
"name": "Tim",
"id": 2
},
{
"name": "Brady",
"id": 2
}
]
You can write a function which goes through each of the entries in the array and removes them if their name has been seen before.
function array_unique_names($array) {
// Copy our input as a temporary new array
$output = $array;
// Keep track of which names we've seen before
$seen_names = [];
foreach ($output as $key => $value) {
// If we've seen a name before, remove it from our output
if (in_array($value['name'], $seen_names)) {
unset($output[$key]);
}
// Otherwise, keep it but add it to the list of seen names
else {
$seen_names[] = $value['name'];
}
}
// Return a re-indexed array
return array_values($output);
}
$data = // Your JSON input string
$array = json_decode($data, TRUE);
$array = array_unique_names($array);
$result = json_encode($array);
I am trying to adhere to an integration requirement of having multiple items with the same key names, including its meta data into a main array to properly json_encode.
I have tried splitting out and joining arrays, array_push. The only workable solution I have is to manually build this part of the json package. Any help would be greatly appreciated.
Here is a sample of what I am struggling with:
$message_pack["Header"]["Sequence"] = 'TEST1';
$message_pack["Header"]["TC"] = "1";
$message_pack["ItemDetail"]["ItemName"] = "Item1";
$message_pack["ItemDetail"]["ItemCode"] = "123";
$message_pack["ItemDetail"]["Itemname"] = "Item2";
$message_pack["ItemDetail"]["ItemCode"] = "234";
$json_msg = json_encode($message_pack);
This will obviously only take the last value passed to the matching key name.
I need to adhere to this json format:
{
"Header": {
"Sequence": "TEST1",
"TC": "1",
},
"ItemDetail": [{
"ItemName": "Item1",
"ItemCode": "123" }
{ "ItemName": "Item2",
"ItemCode": "234" }]
}
You need to make "ItemDetail" an array, else you'll overwrite $message_pack["ItemDetail"]["Itemname"] and $message_pack["ItemDetail"]["ItemCode"]:
<?php
$message_pack["Header"]["Sequence"] = 'TEST1';
$message_pack["Header"]["TC"] = "1";
$message_pack["ItemDetail"][] = ["ItemName" => "Item1", 'ItemCode' => 123];
$message_pack["ItemDetail"][] = ["ItemName" => "Item2", 'ItemCode' => 234];
$json_msg = json_encode($message_pack, JSON_PRETTY_PRINT);
echo ($json_msg);
will output:
{
"Header": {
"Sequence": "TEST1",
"TC": "1"
},
"ItemDetail": [
{
"ItemName": "Item1",
"ItemCode": 123
},
{
"ItemName": "Item2",
"ItemCode": 234
}
]
}
I want to reindex my array both key and values in PHP,
example if delete data: "2" , data 3 will be reindex to 2 and values inside of array 3 {sequence : 3 "ssdummy tossssdo 3"} will be change to {sequence : 2 "ssdummy tossssdo 3"}
{
"sequence": 2,
"data": {
"1": {"sequence": "1", "todo": "dummy todo"},
"2": {"sequence": "2", "todo": "dummy todo 2"},
"3": {"sequence": "3", "todo": "ssdummy tossssdo 3"},}
}
First, you can convert your values to a array, as the input is a json. Then parse the array, to remove the required value.
After parsing the array, you can convert it back to json (if it is needed).
The next script remove the value indicated in the $valueToRemove variable.
<?php
$jsonValues = '{
"sequence": 2,
"data": {
"1": {"sequence": "1", "todo": "dummy todo"},
"2": {"sequence": "2", "todo": "dummy todo 2"},
"3": {"sequence": "3", "todo": "ssdummy tossssdo 3"}
}
}';
$valueToRemove = 2;
$arrayValues = json_decode($jsonValues, true);
$oldData = $arrayValues['data'];
$newData = array();
$counter = 0;
foreach ($oldData as $oldIndex => $oldValue) {
if ($valueToRemove != $oldIndex) {
$counter++;
$newData[$counter] = array(
'sequence' => $counter,
'todo' => $oldValue['todo']
);
}
}
$arrayValues['data'] = $newData;
$jsonValues = json_encode($arrayValues);
var_dump($jsonValues);
?>
I have the following output from the script:
{"sequence":2,"data":{"1":{"sequence":1,"todo":"dummy todo"},"2":{"sequence":2,"todo":"ssdummy tossssdo 3"}}}
In PHP, I'd like to convert an array of objects like the following to a PHP array, using one of the properties as the associative array keys.
[
{ "id": 2, "name": "Suzy" },
{ "id": 3, "name": "Joe" },
{ "id": 4, "name": "Sara" }
]
like this...
[
2 => "Suzy",
3 => "Joe",
4 => "Sara"
]
I can't use array_map because you can't set the keys from my understanding, but I'm wondering if there's a one-liner way to do it without a foreach loop.
To be clear, I want to maintain the keys in the output array, not puts the original keys inside the new array values like they do here: PHP's array_map including keys
It appears by "object" you mean a JSON object. Given that, you can use array_column() to pull out a single column from each row, and then array_combine() to use one column for the keys and another for the values:
$json = '[
{ "id": 2, "name": "Suzy" },
{ "id": 3, "name": "Joe" },
{ "id": 4, "name": "Sara" }
]';
$array = json_decode($json, true);
$out = array_combine(array_column($array, 'id'), array_column($array, 'name'));
print_r($out);
Yields:
Array
(
[2] => Suzy
[3] => Joe
[4] => Sara
)
2 liners and has a foreach though.
<?php
$json = '[
{ "id": 2, "name": "Suzy" },
{ "id": 3, "name": "Joe" },
{ "id": 4, "name": "Sara" }
]';
$new_array = [];
foreach(json_decode($json,true) as $each_object) $new_array[$each_object['id']] = $each_object['name'];
print_r($new_array);
$json = '[
{ "id": 2, "name": "Suzy" },
{ "id": 3, "name": "Joe" },
{ "id": 4, "name": "Sara" }
]';
$array = json_decode($json, true);
$result = array_column($array, 'name', 'id');
I have a multidimensional JSON array that I need to add values to. The JSON array is external and I cannot change its format.
I've tried doing 3 foreach loops, but then I get myself lost in how to add data to the array. I keep catching myself stuck in a loop.
Here's the JSON:
{
"positions": [{
"report_at": "2017-03-13 20:04:10",
"elev": "0",
"dir": "0",
"id": "1"
}, {
"report_at": "2017-03-07 00:28:14",
"elev": "1240",
"dir": "89",
"id": "2"
}]
}
I have unique data I need to add to id 1, and another set of unique data I need to add to id 2.
Here's what I've tried:
$data = json_decode( $result, true );
foreach ( $data as $d ) {
foreach ( $d as $key => $data ) {
if ( $data['id'] == '1' ) {
$data[] = array(
"online_status" => "1",
"name" => "Test User",
);
} elseif ( $data['id'] == '2' ) {
$data[] = array(
"online_status" => "0",
"name" => "Another User",
);
}
}
}
$json = json_encode( $data );
echo $json;
I think once I can get this figured out, then I can pull data from MySQL, build small arrays based off that data, then add those to these sub-arrays where the ID matches the SQL ID. Any help is appreciated.
JSON seems to be just object with "positions" field which is array, you need to modify.
$data = json_decode($json, TRUE);
foreach ($data['positions'] as &$userInfo) {
if ($userInfo['id'] == 1) {
$userInfo['online_status'] = 'offline';
$userInfo['name'] = 'Test user';
}
}
echo json_encode($data);
Notice "&" sign in foreach, which means, that modification made within foreach, will be stored to original array.
Also you should be aware of key=>value naming in foreach. Your second foreach creates variable named $data, which means, that you are loosing pointer to original array!
Use the following approach:
$data = json_decode($result, true);
foreach ($data['positions'] as &$item) {
if ($item['id'] == "1") {
$item = array_merge($item, ["online_status" => "1", "name" => "Test User"]);
} else if ($item['id'] == "2") {
$item = array_merge($item, ["online_status" => "0", "name" => "Another User"]);
}
}
$json = json_encode($data, JSON_PRETTY_PRINT);
echo $json;
The output:
{
"positions": [
{
"report_at": "2017-03-13 20:04:10",
"elev": "0",
"dir": "0",
"id": "1",
"online_status": "1",
"name": "Test User"
},
{
"report_at": "2017-03-07 00:28:14",
"elev": "1240",
"dir": "89",
"id": "2",
"online_status": "0",
"name": "Another User"
}
]
}