Reindex Array values - php

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

Related

PHP: remove from array of objects all duplicates by key, except first one

I have the following associative array of objects:
[
0: {
"score": "value2",
"number": "1",
"finalScore": "-1"
},
1: {
"score": "value3",
"number": "2",
"finalScore": "5"
},
2: {
"score": "value4",
"number": "2",
"finalScore": "5"
},
3: {
"score": "value5",
"number": "3",
"finalScore": "-1"
}
]
Please, have in mind the following format is the prettified JSON string on the browser, after returning it from PHP through an echo json_encode($result)
I need to filter it based on the number property value, in order to remove all duplicates with the same value for the number property except the first one. This means that if two or more objects share the same value for number, only the first one should remain.
Given this explanation, the filtered array from the example above would result on:
[
0: {
"score": "value2",
"number": "1",
"finalScore": "-1"
},
1: {
"score": "value3",
"number": "2",
"finalScore": "5"
},
2: {
"score": "value5",
"number": "3",
"finalScore": "-1"
}
]
I have made several attempts, the closest I've been is this funcion:
function array_iunique($array) {
$lowered = array_map('strtolower', $array);
return array_intersect_key($array, array_unique($lowered));
}
Sounds pretty straight forward to me: you iterate over the input array and accept the elements only if the output does not yet contain such a candidate...
<?php
$input = json_decode(<<<EOT
[
{
"score": "value2",
"number": "1",
"finalScore": "-1"
}, {
"score": "value3",
"number": "2",
"finalScore": "5"
}, {
"score": "value4",
"number": "2",
"finalScore": "5"
}, {
"score": "value5",
"number": "3",
"finalScore": "-1"
}
]
EOT);
$output = [];
array_walk($input, function ($entry) use (&$output) {
if (!array_key_exists($entry->number, $output)) {
$output[$entry->number] = $entry;
}
});
print_r(array_values($output));
The output obviously is:
Array
(
[0] => stdClass Object
(
[score] => value2
[number] => 1
[finalScore] => -1
)
[1] => stdClass Object
(
[score] => value3
[number] => 2
[finalScore] => 5
)
[2] => stdClass Object
(
[score] => value5
[number] => 3
[finalScore] => -1
)
)
Simple approache:
Firstly, convert data from json format to array of scores using json_decode with second args true.
Secondly, create three variable one for output $scores_filtered, second to keep track only unique numbers and $index to keep the order ascending of $scores_filtered array.
Thirdly, iterate over the array of score and check if the number first time occures (meaning doesn't exist in array $unique_numbers) if So, store it in $unique_numbers. get that score and store in $scores_filtered array.
$json = '[{
"score": "value2",
"number": "1",
"finalScore": "-1"
},{
"score": "value3",
"number": "2",
"finalScore": "5"
},{
"score": "value4",
"number": "2",
"finalScore": "5"
},{
"score": "value5",
"number": "3",
"finalScore": "-1"
}
]';
$scores = json_decode($json, true);
$scores_filtered = [];
$unique_numbers = [];
$index = 0;
for($i = 0; $i < count($scores); $i++) {
$score = $scores[$i];
if(!in_array($score['number'], $unique_numbers)){
$unique_numbers[] = $score['number'];
$scores_filtered[$index]["score"] = $score["score"];
$scores_filtered[$index]["number"] = $score["number"];
$scores_filtered[$index]["finalScore"] = $score["finalScore"];
$index += 1;
}
}
Output:
echo "<pre>";
print_r(json_encode($scores_filtered, JSON_PRETTY_PRINT));
/*
[
{
"score": "value2",
"number": "1",
"finalScore": "-1"
},
{
"score": "value3",
"number": "2",
"finalScore": "5"
},
{
"score": "value5",
"number": "3",
"finalScore": "-1"
}
]
*/

Array splice with key name

I have 2 arrays ($data_1 & $data_2) which have different value but have a relation, I want to merge those array, completely with key name
$data_1 =
'[
{
"fruit": "apple",
"weight": "15"
},
{
"fruit": "durian",
"weight": "50"
},
{
"fruit": "orange",
"weight": "10"
}
]';
$data_2 =
'[
{
"color": "red",
"thorn": "no"
},
{
"color": "green",
"thorn": "yes"
},
{
"color": "orange",
"thorn": "no"
}
]';
but I want to combine those array, then I have a full data like this:
$full_data =
'[
{
"fruit": "apple",
"weight": "15",
"color": "red",
"thorn": "no"
},
{
"fruit": "durian",
"weight": "50",
"color": "green",
"thorn": "yes"
},
{
"fruit": "orange",
"weight": "10",
"color": "orange",
"thorn": "no"
}
]';
I tried with array_splice()
for ($i=0; $i < count($data_2); $i++) {
array_splice($data_1[$i], 0, 0, $data_2[$i]);
}
but it returns with '0' and '1' not original key name...
'[
{
"fruit": "apple",
"weight": "15",
"0": "red",
"1": "no"
},
{
"fruit": "durian",
"weight": "50",
"0": "green",
"1": "yes"
},
{
"fruit": "orange",
"weight": "10",
"0": "orange",
"1": "no"
}
]';
I want to replace that '0' and '1' into the original key names
Use array_merge to merge two arrays.
$full_data = [];
for ($i=0; $i < count($data_2); $i++) {
$full_data[$i] = array_merge($data_1[$i], $data_2[$i]);
}
Simply, you could do it by
convert two arrays format json into two php arrays using json_decode function.
iterate over one of them and fill $full_data with values of two arrays respectively.
display the array with format json using json_encode function.
// 1.
$data1 = json_decode($data_1,true);
$data2 = json_decode($data_2,true);
// 2.
$full_data = [];
for ($i=0; $i < count($data1); $i++) {
$full_data[$i] = $data1[$i] + $data2[$i];
}
// 3.
echo(json_encode($full_data));
/*
[
{"fruit":"apple","weight":"15","color":"red","thorn":"no"},
{"fruit":"durian","weight":"50","color":"green","thorn":"yes"},
{"fruit":"orange","weight":"10","color":"orange","thorn":"no"}
]
*/

How can i update or change in array using PHP

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

Rewrite json in loop

I have an array, which i wrote like a table for more reability.
[{
"id": "1",
"title": "boune",
"value": "3"
}, {
"id": "2",
"title": "check",
"value": "4"
}, {
"id": "3",
"title": "boune",
"value": "5"
}]
As the result of what i want to see is this json, where 'value' of identical 'titles' united inside [] brackets. I am very newbie in php. I undestand that i need for loop to sort query result, but can`t heck...Cant even put my mind to it...
[{
"id":"1",
"title": "boune",
"value": [3, 5]
}]
<?php
$json = '[{"id":"1","title":"boune","value":"3"},{"id":"2","title":"check","value":"4"},{"id":"3","title":"boune","value":"5"}]';
$json_data = json_decode($json,true);
function accumulateValuesByTitle($json_data){
$hash = [];
foreach($json_data as $each_record){
if(isset($hash[$each_record['title']])){
$hash[$each_record['title']]['value'][] = $each_record['value'];
if($hash[$each_record['title']]['id'] > $each_record['id']){
$hash[$each_record['title']]['id'] = $each_record['id'];
}
}else{
$hash[$each_record['title']] = $each_record;
$hash[$each_record['title']]['value'] = [$hash[$each_record['title']]['value']];
}
}
return array_values($hash);
}
$modified_data = accumulateValuesByTitle($json_data);
echo json_encode($modified_data);

Search elements of an array by key value

I have the following PHP code which searches the array by the key name and returns result equals to the search. Just for curiosity how can I do that, that no matter what I search for the result will be elements where the name key value equals "A"? Shortly how can I retrieve elements where name is "A" ?
I tried the following but does´t work:
$jSearchResult[] = $ajProducts[$i]->name = "A";
Please help me cause I just simply can´t figure out how to retrive elements of an array by key value, however I am sure it must be something very simple.
<?php
//DATA coming from the BROWSER
$sSearch = $_GET['search'];
//TURN it into UPPERCASE
strtoupper( $sSearch );
//GETTING from the TEXT FILE:
$sajProducts = file_get_contents( 'products.txt' );
$ajProducts = json_decode( $sajProducts );
$match_found = false;
//Collect all matching result in an array
$jSearchResult = array();
//LOOPING THROUGH THE ARRAY OF PRODUCTS
for ( $i=0; $i< count( $ajProducts ); $i++ ) {
if ( $sSearch == $ajProducts[$i]->name ) {
$jSearchResult[] = $ajProducts[$i]->name;
$match_found = true;
}
}
//if there is a match display the product
if ( $match_found ) {
echo json_encode ( $jSearchResult );
exit;
}
//if not display ALL products
else {
echo json_encode ( $ajProducts );
exit;
}
?>
$ajProducts looks like this:
[
{
"id": "59d278cae7017",
"name": "A",
"price": "1",
"quantity": 2,
"image": "img_webshop\/productimage-59d74304917c2.jpg"
},
{
"id": "59d27e20c8028",
"name": "A",
"price": "2",
"quantity": 1,
"image": "img_webshop\/productimage-59d743233c0cf.jpg"
},
{
"id": "59d6a7ae16d15",
"name": "A",
"price": "3",
"quantity": 2,
"image": "img_webshop\/productimage-59d743392fbb5.jpg"
},
{
"id": "59d6d6ee5f752",
"name": "A",
"price": "4",
"quantity": 1,
"image": "img_webshop\/productimage-59d74352d5b94.jpg"
},
{
"id": "59d743d207bd5",
"name": "B",
"price": "5",
"quantity": 1,
"image": "img_webshop\/productimage-59d743d1e6e64.jpg"
},
{
"id": "59d74451225ac",
"name": "B",
"price": "6",
"quantity": 0,
"image": "img_webshop\/productimage-59d7445120871.jpg"
},
{
"id": "59e0d992d1f3b",
"name": "C",
"price": "6",
"quantity": 2,
"image": "img_webshop\/productimage-59e725ac79583.jpg"
}
]
There is a php function that does just that: http://php.net/array_filter
$searchResult = array_filter($ajProducts, function ($product) {
return $product->name === 'A';
});
This will get you all objects in $ajProducts having name property set to 'A'.
To see if there're any results:
$matchFound = !empty($searchResult);
If you want to match elements where the name key value equals "A", then you can just make a check with value of name key is equal to "A" like -
foreach ($ajProducts as $ajProduct ) {
if ( "A" == $ajProduct->name ) {
$jSearchResult[] = $ajProduct->name;
$match_found = true;
}
}

Categories