Find similar items in PHP object - php

I've been trying and trying on this and can't seem to work it out on my own.
So could someone please show me the direction I want to take with this?
I want to be able to implode the object items which contain the string - grade_id.
I've tried getting them all by using array_filter() etc. However seems to not return back the right values.
array_keys() doesn't bring anything back either to try and match array_keys with a preg_match.
I'm just looking for some guidance for this, you don't have to give me a full answered answer, just a point in the right direction.
meeting Object
(
[errors] => 0
[id] => 1
[school_id] => 1
[staff_id] => 2
[grade_id] => 85
[grade_id_2] => 0
[grade_id_3] => 0
[grade_id_4] => 0
[grade_id_5] => 0
[grade_id_6] => 0
[grade_id_7] => 0
[grade_id_8] => 0
[grade_id_9] => 0
[grade_id_10] => 0
[inserted] => 2018-02-19 11:46:13
[updated] => 2018-02-19 12:00:31
)
Result i'm looking for is: (I'm wanting to find a way without using a loop "If possible")
$grade_ids = "85";

You can do this if you convert your object into array:
$array = (array)$object;
/* find keys in array that contain 'grade_id' */
$keys = preg_grep('/grade_id/', array_keys($array));
/* discard other array elements */
$filtered = array_intersect_key($array, array_flip($keys));
$result = implode(',', $filtered);

You can use array_walk_recursive(), I try like this code:
$var = array('meeting'=> array("errors" => 0,
"id" => 1,
"school_id" => 1,
"staff_id" => 2,
"grade_id" => 85,
"grade_id_2" => 0,
"grade_id_3" => 0,
"grade_id_4" => 0,
"grade_id_5" => 0,
"grade_id_6" => 0,
"grade_id_7" => 0,
"grade_id_8" => 0,
"grade_id_9" => 0,
"grade_id_10" => 0,
"inserted" => "2018-02-19 11:46:13",
"updated" => "2018-02-19 12:00:31"));
$uniques = array();
array_walk_recursive($var, function($val, $key) use (&$uniques){
$i=2;
if($key == 'grade_id') {
$uniques[] = $val;
} if($key == 'grade_id_'.$i) {
$uniques[] = $val;
}
$i++;
});
$uniques = array_unique($uniques);
print_r($uniques);
and output is:
Array ( [0] => 85 [1] => 0 )

Related

Defining values to specific indexes of a multidimensional array [duplicate]

This question already has answers here:
How to access and manipulate multi-dimensional array by key names / path?
(10 answers)
Closed 1 year ago.
I'm trying to create a function that will assign new values to a specific indexes in a multidimensional array:
I Have the array that looks like this:
data[i]['checkin'];
data[i]['checkout'];
data[i]['content'][x]['price'];
data[i]['content'][x]['profit'];
data[i]['content'][x]['exchangerate'];
first parameter of my function will get the array, And second parameter will get the indexes that I want to redefine:
For example:
function defineNewValues(&$arr, $keys) {
//logic
}
Call the function:
defineNewValues($myArray, [
'data.*.content.*.price' => 0,
'data.*.content.*.profit => 0,
]);
Im beliving that recursion is the key for my problem ,
But not really know how to solve it.
Thank You.
could something like this be okay?
I only ask you to study this code not to implement it, for the simple reason that in the future you may have the same type of problem.
function setValue($key,$value,&$array){
$find_parts = explode(".", $key);
$find = $find_parts[0]??null;
if ($find!=null){
if ($find == "*"){
array_shift($find_parts);
foreach($array as &$sub_array){
setValue(implode(".",$find_parts),$value,$sub_array);
}
}else{
if (count($find_parts)>1){
if (array_key_exists($find,$array)){
array_shift($find_parts);
setValue(implode(".",$find_parts),$value,$array[$find]);
}
}else{
if (array_key_exists($find,$array)){
$array[$find] = $value;
}
}
}
}
}
function defineNewValues(&$arr, $keys) {
foreach($keys as $key=>$value){
setValue($key,$value,$arr);
}
}
$myArray=[
"data"=>[
"a"=>[
"content"=>[
"aa"=>[
"price" => 3,
"profit" => 2,
"other" => 1
],
"ab"=>[
"price" => 3,
"profit" => 2,
"other" => 2
]
]
],
"b"=>[
"content"=>[
"ba"=>[
"price" => 3,
"profit" => 2,
"other" => 4
],
"bb"=>[
"price" => 3,
"profit" => 2,
"other" => 5
]
]
],
]
];
defineNewValues($myArray, [
"data.*.content.*.price" => 0,
"data.*.content.*.profit" => 0,
]);
print_r($myArray);
/* OUTPUT
Array
(
[data] => Array
(
[a] => Array
(
[content] => Array
(
[aa] => Array
(
[price] => 0
[profit] => 0
[other] => 1
)
[ab] => Array
(
[price] => 0
[profit] => 0
[other] => 2
)
)
)
[b] => Array
(
[content] => Array
(
[ba] => Array
(
[price] => 0
[profit] => 0
[other] => 4
)
[bb] => Array
(
[price] => 0
[profit] => 0
[other] => 5
)
)
)
)
)
*/
Because the keys you want to replace only occur at one level of the data, the solution doesn't really need to take the entire array structure into account. You can just replace every price and profit key.
array_walk_recursive($example, function(&$value, $key) {
if (in_array($key, ['price', 'profit'])) {
$value = 0;
}
});
Based on your comment on the other answer, my opinion on the "correct and professional way" is that we should try to solve the problem in the simplest way possible, because simple solutions are easy to maintain.

get the maximum value of the associative array in php [duplicate]

This question already has answers here:
Hightest value of an associative array
(4 answers)
Closed 4 years ago.
I have the following array
Array
(
[anger] => 0
[disgust] => 20
[fear] => 0
[joy] => 22.853
[sadness] => 0
[surprise] => 0
)
Array
(
[anger] => 0
[disgust] => 20
[fear] => 0
[joy] => 22.853
[sadness] => 0
[surprise] => 0
)
I want to get key of the maximum value from the array that is joy from the above array.
Thank you for helping in advance.
$key = array_keys($yourArray,max($yourArray));
You can do this with 2 steps given below:
Get the max value:
$value = max($array);
Get the corresponding key:
$key = array_search($value, $array);
<?php
$array = array(
Array
(
'anger' => 0,
'disgust' => 20,
'fear' => 0,
'joy' => 22.853,
'sadness' => 0,
'surprise' => 0
),
Array
(
'anger' => 0,
'disgust' => 20,
'fear' => 0,
'joy' => 22.853,
'sadness' => 6660,
'surprise' => 0
)
);
for ($i=0; $i < count($array); $i++) {
$maxs = array_keys($array[$i], max($array[$i]));
print_r($maxs);
}
?>
OUTPUT:
Array ( [0] => joy ) Array ( [0] => sadness )
Hope this will help you
Thanks
Muthu
#Niki, above answers are appreciable. Here I've tried to present you in my way. May be, it can be similar to other answers. I will try to find other ways to do the same and update the answer.
Try it online at http://rextester.com/MDGZ18118.
PHP code »
<?php //php 7.0.8
$arr1 = Array
(
"anger" => 0,
"disgust" => 20,
"fear" => 0,
"joy" => 22.853,
"sadness" => 0,
"surprise" => 0,
);
$arr2 = Array
(
"anger" => 0,
"disgust" => 20,
"fear" => 0,
"joy" => 22.853,
"sadness" => 0,
"surprise" => 0,
);
$ret = print_r($arr1); // print_r() returns 1, if we will not store it in any variable then it will be printed on screen.
echo "\n"; // echo "<br>"; for browser
$ret = print_r($arr2);
// Finding key of max element
echo array_search(max($arr1), $arr1);
echo("\n"); // echo "<br>"; for browser
echo array_search(max($arr2), $arr2);
?>
Output »
Array
(
[anger] => 0
[disgust] => 20
[fear] => 0
[joy] => 22.853
[sadness] => 0
[surprise] => 0
)
Array
(
[anger] => 0
[disgust] => 20
[fear] => 0
[joy] => 22.853
[sadness] => 0
[surprise] => 0
)
joy
joy

fill in the multidimensional array with missing keys

I have the following multidimensional array. I had to create keys the way it looks to group them accordingly.
Array
(
[Oranges] => Array
(
[Name] => Oranges
[l.VA123] => 17
[l.MA123] => 12
[l.GA123] => 9
[l.CT123] => 5
)
[Apple] => Array
(
[Name] => Apple
[l.CA123] => 13
)
[Grapes] => Array
(
[Name] => Grapes
[l.WI123] => 8
[l.FL123] => 5
)
)
However, I need all the subarrays to have the same keys. Missing ones should be filled with a value of 0. The final array should be like below so that all subarrays have equal length.
Array
(
[Oranges] => Array
(
[Name] => Oranges
[l.VA123] => 17
[l.MA123] => 12
[l.GA123] => 9
[l.CT123] => 5
[l.CA123] => 0
[l.WI123] => 0
[l.FL123] => 0
)
[Apple] => Array
(
[Name] => Apple
[l.CA123] => 13
[l.WI123] => 0
[l.FL123] => 0
[l.VA123] => 0
[l.MA123] => 0
[l.GA123] => 0
[l.CT123] => 0
)
[Grapes] => Array
(
[Name] => Grapes
[l.WI123] => 8
[l.FL123] => 5
[l.CA123] => 0
[l.VA123] => 0
[l.MA123] => 0
[l.GA123] => 0
[l.CT123] => 0
)
)
You need a simple + operator. As from manual:
The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored.
$items = Array
(
'Oranges' => Array
(
'Name' => 'Oranges',
'l.VA123' => 17,
'l.MA123' => 12,
'l.GA123' => 9,
'l.CT123' => 5,
),
'Apple' => Array
(
'Name' => 'Apple',
'l.CA123' => 13,
),
'Grapes' => Array
(
'Name' => 'Grapes',
'l.WI123' => 8,
'l.FL123' => 5,
),
);
// static keys
$keys = [
'l.VA123' => 0,
'l.MA123' => 0,
'l.GA123' => 0,
'l.CT123' => 0,
'l.CA123' => 0,
'l.WI123' => 0,
'l.FL123' => 0,
];
// keys generated from source array, tricky approach
$keys = array_fill_keys(
// here we merge all elements of `$items` into one array
// as keys are repeated - you definitely got all keys that
// can be in `$items`, `array_keys` will give you these keys
// `array_fill_keys` will create array where key is what you need
// and value is 0.
array_keys(call_user_func_array('array_merge', $items)),
0
);
// keys generated from source array, SIMPLE approach
$keys = [];
foreach ($items as $item) {
foreach ($item as $k => $v) {
if ($k != 'Name') {
$keys[$k] = 0;
}
}
}
foreach ($items as &$item) {
$item = $item + $keys;
}
print_r($items);
Probably someone can come up with something more efficient, but without a list of keys that you want, I think you'll need to take a couple of passes of the array:
<?php
$fruits = [
"Oranges"=>["Name"=>"Oranges", "l.VA123"=>17, "l.MA123"=>12, "1.GA123"=>9, "1.CT123"=>5],
"Apple"=>["Name"=>"Apple", "1.CA123"=>13],
"Grapes"=>["Name"=>"Grapes", "1.WI123"=>8, "1.FL123"=>5]
];
$keys = [];
foreach ($fruits as $fruit) {
unset($fruit["Name"]);
$keys = array_merge($keys, array_keys($fruit));
}
$keys = array_fill_keys(array_unique($keys), 0);
foreach ($fruits as &$fruit) {
$fruit = array_merge($keys, $fruit);
}
print_r($fruits);
Since all keys and default values are "known", create an associative array, use a foreach() and modify the rows by reference, and use the union-assignment (combined) operator. This will allow the original values to overwrite the default values.
Code: (Demo)
$keys = [
'l.VA123' => 0,
'l.MA123' => 0,
'l.GA123' => 0,
'l.CT123' => 0,
'l.CA123' => 0,
'l.WI123' => 0,
'l.FL123' => 0,
];
foreach ($items as &$row) {
$row += $keys;
}
var_export($items);
If you want the keys to be consistently positioned, then use array_replace() or array_merge() instead of the union assignment operator.
Code: (Demo)
foreach ($items as &$row) {
$row = array_replace($keys, $row);
}

php Sum specific value from multidimensional array [duplicate]

This question already has answers here:
How to sum all column values in multi-dimensional array?
(20 answers)
Closed 1 year ago.
I have array like this :
Array
(
[0] => Array
(
[impr] => 800000
[clicks] => 500
[ctr] => 0.000625
[cvr] => 0.04
[cpc] => 0.14024
[cpm] => 0.08765
[cpa] => 3.51
)
[1] => Array
(
[impr] => 889000
[clicks] => 600
[ctr] => 0.000625
[cvr] => 0.08
[cpc] => 0.34024
[cpm] => 0.08765
[cpa] => 4.41
)
)
I want to sum that array and get result like this
Array
(
[impr] => 1689000
[clicks] => 1100
[ctr] => 0.0025
[cvr] => 0.12
[cpc] => 0.96096
[cpm] => 0.1753
[cpa] => 7.92
)
I trying to using
array_sum()
with looping my array to that array_sum, but I getting error like this
array_sum() expects parameter 1 to be array, integer given
And even try looping with foreach and using += for sum the value, but the result is not I want
the result is 800000889000
Can anyone suggest me the better code for getting my result like I want
First create an array that will contain the sums:
$sumArray = array(
"impr" => 0,
"clicks" => 0,
"ctr" => 0,
"cvr" => 0,
"cpc" => 0,
"cpm" => 0,
"cpa" => 0,
);
Then do the calculating:
foreach ($oldArray as $row)
{
foreach ($rows as $key => $value)
{
$sumArray[$key] += $value;
}
}
Then to view your results, just do:
print_r($sumArray);
NOTE: I am assuming that the keys that you have in your original array don't have the brackets around them, however if the actual key strings do have the brackets, then use the following code for creating $sumArray:
$sumArray = array(
"[impr]" => 0,
"[clicks]" => 0,
"[ctr]" => 0,
"[cvr]" => 0,
"[cpc]" => 0,
"[cpm]" => 0,
"[cpa]" => 0,
);

get set elements from array php

I have array in php :
Array
(
[id] => 1
[comp_id] => 1
[transaction_purpose] => 0
[source_of_funds] => 1
[beneficiary_relationship] => 0
[cus_occupation] => 0
[cus_id_image_2] => 0
[cus_id_image_3] => 0
[ben_id_type] => 0
[ben_id_number] => 1
)
I want to get only array key=>value pair if the valie is 1.
result array should be:
Array
(
[id] => 1
[comp_id] => 1
[source_of_funds] => 1
[ben_id_number] => 1
)
I tried with:
$returnArray = array();
foreach($mainArray as $r){
if($r>0){
array_push($returnArray, $mainArray);
}
}
But, It's giving me 4 times main array. Is there any way to achieve this? Thanks..
Just use array_filter():
$newarray = array_filter($array, function($var) {
return ($var === 1);
});
$newarray = array_filter($array);
Demo
$array = array(
'id' => 1,
'comp_id' => 1,
'transaction_purpose' => 0,
'source_of_funds' => 1,
'beneficiary_relationship' => 0,
'cus_occupation' => 0,
'cus_id_image_2' => 0,
'cus_id_image_3' => 0,
'ben_id_type' => 0,
'ben_id_number' => 1
);
$newarray = array_filter($array);
print_r($newarray);
Array
(
[id] => 1
[comp_id] => 1
[source_of_funds] => 1
[ben_id_number] => 1
)
Try this:
$returnArray = array_filter($result);
You can see PHP's array_filter function for more info.
Well, what else are you expecting to happen?
array_push($returnArray, $mainArray);
If you find an element which has >0 value, you push the ENTIRE original array onto the new one, not just the key/value you just tested.
You probably want:
$newarr = array();
foreach($mainArray as $key => $value) {
if ($value > 0) {
$newarr[$key] = $value;
}
}

Categories