Extract equal values for multidimensional array in php - php

I have this problem. I have a multidimensional json array (don't ask - legacy code). I convert it to PHP array. I need to extract all KEYS that have EQUAL VALUE (in my case "666"). I need each key to be assign to a SEPARATE variable. In my code I succeeded to fetch the keys but I can assign them only to another array or all at once to a single variable. Please HELP!!!
Love V
Here is the code:
<?php
//user input
$in = "666";
$outputZ = '[
{"record_id_001":"1"},
{"record_id_002":"13"},
{"record_id_003":"666"},
{"record_id_004":"72661781"},
{"record_id_005":"8762"},
{"record_id_006":"666"},
{"record_id_007":"8762"},
{"record_id_008":"666"},
{"record_id_009":"8762"},
{"record_id_010":"8762"},
{"record_id_011":"666"}
]';
//convert json to php array
//someArray = json_decode($someJSON, true);
$decoZ = json_decode($outputZ, true);
// TESTING (move to comment latter)
//print_r ($decoZ);
//loop through each array an check for user input
//way 1: assign to new array
foreach($decoZ as $array => $number)
foreach($number as $key => $value)
if (in_array("$in", $number)) {
$var = $key;
$getarray = "'" . $var . "'";
$recnumber = array($getarray);
print_r ($recnumber);
}
//way 2: assign to variable
foreach($decoZ as $array => $number)
foreach($number as $key => $value)
if (in_array("$in", $number)) {
$var = $key;
echo "$var" . " ";
}
?>

You're overwritting your array on each iterations $recnumber = array($getarray);
I would rather follow this logic :
<?php
//user input
$in = "666";
$outputZ = '[
{"record_id_001":"1"},
{"record_id_002":"13"},
{"record_id_003":"666"},
{"record_id_004":"72661781"},
{"record_id_005":"8762"},
{"record_id_006":"666"},
{"record_id_007":"8762"},
{"record_id_008":"666"},
{"record_id_009":"8762"},
{"record_id_010":"8762"},
{"record_id_011":"666"}
]';
$decoZ = json_decode($outputZ, true);
// create empty array
$recnumber = [];
foreach($decoZ as $record)
{
foreach($record as $key => $value)
{
// simply compare input with current value
if ($value === $in)
{
// add the key to the previously created array
$recnumber[] = $key;
}
}
}
var_dump($recnumber);
This outputs :
array(4) {
[0]=>
string(13) "record_id_003"
[1]=>
string(13) "record_id_006"
[2]=>
string(13) "record_id_008"
[3]=>
string(13) "record_id_011"
}

You can simply remap the records.
At the end you can grab them like
$codes666 = $ids['666'];
$outputZ = '[
{"record_id_001":"1"},
{"record_id_002":"13"},
{"record_id_003":"666"},
{"record_id_004":"72661781"},
{"record_id_005":"8762"},
{"record_id_006":"666"},
{"record_id_007":"8762"},
{"record_id_008":"666"},
{"record_id_009":"8762"},
{"record_id_010":"8762"},
{"record_id_011":"666"}
]';
$records = json_decode($outputZ);
$ids = [];
foreach($records as $record) {
foreach($record as $key => $value) {
$ids[(string)$value][] = $key;
}
}
print_r($ids);
Gives
Array
(
[1] => Array
(
[0] => record_id_001
)
[13] => Array
(
[0] => record_id_002
)
[666] => Array
(
[0] => record_id_003
[1] => record_id_006
[2] => record_id_008
[3] => record_id_011
)
[72661781] => Array
(
[0] => record_id_004
)
[8762] => Array
(
[0] => record_id_005
[1] => record_id_007
[2] => record_id_009
[3] => record_id_010
)
)

Related

Associative Array SUM by key value php [duplicate]

This question already has answers here:
Associative array, sum values of the same key
(5 answers)
Closed 2 years ago.
I want to sum an array and grouping them by its key value.
this is the array :
Array
(
[0] => Array
(
[delivery_plan] => 80::2020/07
[additional_amount_usd] => 32.88
)
[1] => Array
(
[delivery_plan] => 80::2020/09
[additional_amount_usd] => 16.44
)
[2] => Array
(
[delivery_plan] => 80::2020/07
[additional_amount_usd] => 32.88
)
)
I want output to be like this :
Array
(
[0] => Array
(
[delivery_plan] => 80::2020/07
[additional_amount_usd] => 65.76
)
[1] => Array
(
[delivery_plan] => 80::2020/09
[additional_amount_usd] => 16.44
)
I have tried using this code, but the output different from my expected result :
$arr = [];
foreach ($section_balance as $sb => $val) {
if(array_key_exists($sb, $arr)){
$arr[$sb] += array_sum($val);
} else {
$arr[$sb] = array_sum($val);
}
}
i've got tis result instead :
Array
(
[0] => 112.88
[1] => 96.44
[2] => 112.88
)
How can i solve this ?
This is one way to do it breaking it down into steps...
1.Create the Array that sums the matching delivery_plans
2.Rebuild the Array as required
<?php
$sum_array = [];
foreach($array as $item) {
if (key_exists($item['delivery_plan'], $sum_array)) {
$sum_array[$item['delivery_plan']] += $item['additional_amount_usd'];
} else {
$sum_array[$item['delivery_plan']] = $item['additional_amount_usd'];
}
}
$final_array = [];
foreach($sum_array as $key => $value) {
$final_array[] = ['delivery_plan' => $key, 'additional_amount_usd' => $value];
}
Refactoring the above so the code is not dependant upon hardcoded index names...
$key_name = 'delivery_plan';
$value_name = 'additional_amount_usd';
$sum_array = [];
foreach($array as $item) {
if (key_exists($item[$key_name], $sum_array)) {
$sum_array[$item[$key_name]] += $item[$value_name];
} else {
$sum_array[$item[$key_name]] = $item[$value_name];
}
}
$final_array = [];
foreach($sum_array as $key => $value) {
$final_array[] = [$key_name => $key, $value_name => $value];
}
And you could then turn that into a function if you so desired...
The result is (using var_dump())
array(2) {
[0]=>
array(2) {
["delivery_plan"]=>
string(13) "80::2020 / 07"
["additional_amount_usd"]=>
float(65.76)
}
[1]=>
array(2) {
["delivery_plan"]=>
string(13) "80::2020 / 09"
["additional_amount_usd"]=>
float(16.44)
}
}
Update:
Also Take a look at the solution provided by Kevin.
3v4l.org/h9Q5L

How can I sort values from an existing array by data type?

I try to determine the data type of each array value from an existing array using foreach() and var_dump().
Let's say I have this array: example:
$arr = ['this','is', 1, 'array', 'for', 1, 'example'];
Now I have to take each value of this field and determine its data type.
I try this:
$str = array();
$int = array();
foreach($arr as $k => $val) {
if(var_dump($arr[$k]) == 'string'){
$str[] = $arr[$k];
} else {
$int[] = $arr[$k];
}
}
In other words, I try to sort the values from an existing array by data type and create a new array with only 'string' values and a second new array with only 'int' values. But it seems that my 'if' condition isn't working properly. How else could I solve this please? Thank you.
You need to use gettype to get the type of a value, not var_dump:
foreach($arr as $k => $val) {
if(gettype($arr[$k]) == 'string'){
$str[] = $arr[$k];
} else {
$int[] = $arr[$k];
}
}
Output:
Array
(
[0] => this
[1] => is
[2] => array
[3] => for
[4] => example
)
Array
(
[0] => 1
[1] => 1
)
Demo on 3v4l.org
Use gettype
$data = array('this','is', 1, 'array', 'for', 1, 'example');
foreach ($data as $value) {
echo gettype($value), "\n";
}

Convert array in string with another array

I have a two array first is:
$array1 = ['settings:rules:key','settings:scrum:way:other'];
I have explode $array1:
$temp_array = explode(":",$array1);
Now I have another array:
$array2 = [settings] => Array
( [rules] => Array
(
[0] => Array
(
[key] =>
[showValueField] => 1
)
)
something like this.
I need to access second array with key given in first array like:
$array2['settings']['rules']['key']
I have to get this keys from first array after explode
You can do it with this kind of loop:
function getVal($path, $arr) {
$current = $arr[array_shift($path)];
while (count($path)) {
$key = array_shift($path);
if (!is_array($current) || !isset($current[$key]))
return false; // protect against non-existing keys
$current = $current[$key];
}
return $current;
}
//example used:
$arr = array("settings" => array("rules" => array("key" => "AAA")));
echo getVal(explode(":",'settings:rules:key'), $arr) . PHP_EOL;

Reverse array elements with specific value

I have an array like this
$array = array( [0] => 'red1', [1] => 'blue1', [2] => 'red2', [3] => 'red3', [4] => 'blue2' );
A want to reverse order of elements with red value only so it looks like this:
$array = array( [0] => 'red3', [1] => 'blue1', [2] => 'red2', [3] => 'red1', [4] => 'blue2' );
I think a possible solution might be to:
Get all the values from the $array that you are looking for and
store them in an array $found
Reverse the values in $found keeping the keys
Replace the values in $array with the values from $found using
the key
For example:
$array = array(0 => 'red1', 1 => 'blue1', 2 => 'red2', 3 => 'red3', 4 => 'blue2');
// First get all the values with 'red' and store them in an array
$found = preg_grep('/red\d+/', $array);
// Reverse the values, keeping the keys
$found = array_combine(
array_keys($found),
array_reverse(
array_values($found)
)
);
// Then replace the values of $array with values having the same keys in $found
$array = array_replace($array, $found);
var_dump($array);
Will result in:
array(5) {
[0]=>
string(4) "red3"
[1]=>
string(5) "blue1"
[2]=>
string(4) "red2"
[3]=>
string(4) "red1"
[4]=>
string(5) "blue2"
}
You can catch red's quote to a new array and sort them.
<?php
$arr = array(
'red1',
'blue1',
'red2',
'red3',
'blue2'
);
$sortArr = array();
for ($i=0; $i < sizeof($arr); $i++) {
if(strstr($arr[$i], "red")){
$sortArr[] = &$arr[$i];
}
}
?>
I think you can do using searching specific words by strpos and sorting array by ksort (sort associative arrays in ascending order, according to the key)
foreach ($array as $key => $value) {
if(strpos($value,"red") !== false){
($key === 0) ? $index = 3 : (($key === 3) ? $index = 0 : $index = 2);
$temp[$index] = $value;
}
else {
$temp[$key] = $value;
}
}
ksort($temp);
var_dump($temp);
[But It will not work in larger array than this]

How can I compare two Arrays and detect if the values are incorrect or missing?

I have to arrays I would like to compare:
$original and $duplicate.
for example here is my original file:
print_r($original);
Array ( [0] => cat423 [1] => dog456 [2] => horse872 [3] => duck082 )
and here is my duplicate:
print_r($dublicate);
Array ( [0] => cat423 [1] => dug356 )
I compare them with array_diff:
$result = array_diff($original, $dublicate);
My result:
Array ( [1] => dog456 [2] => horse872 [3] => duck082 )
So far so good, but I need to make a difference between the values which are incorrect and the values which are completely missing. Is this possible?
A way would be to crawl the entire original array, afterwards you will have two arrays, missings and duplicates.
$original = array("cat423", "dog456", "horse872", "duck082");
$duplicate = array("cat423", "dug356");
$missings = $duplicates = array();
foreach ($original as $val) {
if (in_array($val, $duplicate))
$duplicates[] = $val;
else
$missings[] = $val;
}
If you need the keys as well, you would have to alter the foreach loop like so:
foreach ($original as $key=>$val) {
if (in_array($val, $duplicate))
$duplicates[] = array("key" => $key, "value" => $val);
else
$missings[] = array("key" => $key, "value" => $val);
}
use in_array function
$original = array("cat423", "dog456", "horse872", "duck082");
$duplicate = array("cat423", "dug356");
foreach ($original as $item) {
if(in_array($item, $duplicate))
{
$dup[] = $item;
}
else
{
$miss[] = $item;
}
}
print_r($miss); #Array ( [0] => dog456 [1] => horse872 [2] => duck082 )
print_r($dup); #Array ( [0] => cat423 )
Working Preview

Categories