Adding key=>value pair to existing array with condition - php

Im trying to add a key=>value to a existing array with a specific value.
Im basically looping through a associative array and i want to add a key=>value foreach array that has a specific id:
ex:
[0] => Array
(
[id] => 1
[blah] => value2
)
[1] => Array
(
[id] => 1
[blah] => value2
)
I want to do it so that while
foreach ($array as $arr) {
while $arr['id']==$some_id {
$array['new_key'] .=$some value
then do a array_push
}
}
so $some_value is going to be associated with the specific id.

The while loop doesn't make sense since keys are unique in an associative array. Also, are you sure you want to modify the array while you are looping through it? That may cause problems. Try this:
$tmp = new array();
foreach ($array as $arr) {
if($array['id']==$some_id) {
$tmp['new_key'] = $some_value;
}
}
array_merge($array,$tmp);
A more efficient way is this:
if(in_array($some_id,$array){
$array['new_key'] = $some_value;
}
or if its a key in the array you want to match and not the value...
if(array_key_exists($some_id,$array){
$array['new_key'] = $some_value;
}

When you use:
foreach($array as $arr){
...
}
... the $arr variable is a local copy that is only scoped to that foreach. Anything you add to it will not affect the $array variable. However, if you call $arr by reference:
foreach($array as &$arr){ // notice the &
...
}
... now if you add a new key to that array it will affect the $array through which you are looping.
I hope I understood your question correctly.

If i understood you correctly, this will be the solution:
foreach ($array as $arr) {
if ($arr['id'] == $some_id) {
$arr[] = $some value;
// or: $arr['key'] but when 'key' already exists it will be overwritten
}
}

Related

PHP multidimensional arrays - return value from second key if value from first key exists

So not a stranger to PHP or arrays even, but never had to deal with multidimensional arrays and its doing my head in.
I have the output of a PHP to a server API and need to pull all the mac address values from the (dst_mac) keys, but only on the occasion the category (catname) keys value for each element is emerging-p2p
The format of the array is like this (intermediate keys and values removed for brevity)
[1] => stdClass Object
(
[_id] => 5c8ed5b2b2302604a9b9c78a
[dst_mac] => 78:8a:20:47:60:1d
[srcipGeo] =>
[dstipGeo] => stdClass Object
(
)
[usgipGeo] => stdClass Object
(
)
[catname] => emerging-p2p
)
Any help much appreciated, i know when im out of my depth!
From your example that is an array with a std class. you can use the empty funtion.
//checks if the first key
if (!empty($array[1]->_id)) {
echo $array[1]->dst_mac;
// or do what you want.
}
This example only applies to one array. use a loop to have this dynamically done.
EDIT: My answer was based on your question. Didn't realize you have to check the catname to be 'emerging-p2p' before you get the mac address?
// loop through the array
foreach ($array as $item) {
// checks for the catname
if ($item->catname === 'emerging-p2p') {
// do what you want if the cat name is correct
echo $item->dst_mac;
}
}
Is this what you want?
for($i =0;$i<count($arr);$i++){
if(isset($arr[$i]['catname']) && $arr[$i]['catname']=='emerging-p2p'){
echo $arr[$i]['dst_mac'];
}
}
If there is only one object that has 'emerging-p2p' cat name:
foreach ($your_list_of_objects as $obj) {
if ($obj->catname == 'emerging-p2p') {
return $obj->dst_mac;
}
}
If there are many:
$result = [];
foreach ($your_list_of_objects as $obj) {
if ($obj->catname == 'emerging-p2p') {
$result[]= $obj->dst_mac;
}
}
return $result;
Use for loop.
for($i =0; $i<=count($arr); $i++){
if(arr[$i]['catname']=='emerging-p2p'){
echo arr[$i]['dst_mac'];
}
}
To fetch all the mac where catname is emerging-p2p
//Assuming $arr has array of objects
$result_array = array_filter($arr, function($obj){
if ($obj->catname == 'emerging-p2p') {
return true;
}
return false;
});
foreach ($result_array as $value) {
echo $value->dst_mac;
}
You can use array_column if you need only mac address on the basis of catname.
$arr = json_decode(json_encode($arr),true); // to cast it as array
$temp = array_column($arr, 'dst_mac', 'catname');
echo $temp['emerging-p2p'];
Working demo.

Multidimensional array keys to variable

sadly i havent found any solution yet.
I have an multidimensional array which looks like this:
Array
(
[0] => Array
(
[Symbol] => CASY.US
[Position] => 169873920
)
[1] => Array
(
[Symbol] => US500
[Position] => 168037428
) )
Now i want to write the name of the keys of the inner array into variables so that i have these variables with the values:
$col1 = "Symbol"
$col2 = "Position"
How can i achieve that? Somehow with a couple of foreach loops?
Background: After that i want to check if the columns have the right name for a validation.
Thanks in advance!
Loop nested and save the keys to an array with "col" and an integer that you later can (if you really must extract), but I recommend to keep them in the array.
foreach($array as $subarray){
$i = 1;
foreach($subarray as $key => $val){
$keys["col" . $i] = $key;
$i++;
}
break; // no need to keep looping if the array is uniform
}
//if you must:
extract($keys);
https://3v4l.org/ALVtp
If the subarrays are not the same then you need to loop all subarrays and see if the key has already been saved, if not save it else skip it.
$keys =[];
$i = 1;
foreach($array as $subarray){
foreach($subarray as $key => $val){
if(!in_array($key, $keys)){
$keys["col" . $i] = $key;
$i++;
}
}
}
var_dump($keys);
//if you must:
extract($keys);
var_dump($col1, $col2, $col3);
https://3v4l.org/EklPK
Honestly I would do something like this:
$required = array_flip(['Symbol', 'Position']); //flip because I am lazy like that ['Symbol'=>0, 'Position'=>1]
foreach($array as $subarray){
$diff = array_diff_key($required, $subarray);
//prints any keys in $required that are not in $subarray
print_r($diff);
if(!empty($diff)){
//some required keys were missed
}
}
While its not clear how you validate these the reason is as I explained in this comment
it still doesn't solve the problem, as you really have no way to know what the keys will be (if they are not uniform). So with my example foo is $col3 what if I have bar later that's $col4 what if the order is different next time.... they will be different numbers. Sure it's a few what if's but you have no guarantees here.
By dynamically numbering the keys, if the structure of the array ever changes you would have no idea what those dynamic variables contain, and as such no idea how to validate them.
So even if you manage to make this work, if your data ever changes you going to have to re-visit the code.
In any case if your wanting to see if each array contains the keys it needs to, what I put above would be a more sane way to do it.

array_merge function doesn't work properly in Laravel

In my project i'm split an array index value based on regex value. but when i want merge all array together the merge function doesn't merge.
Here is my code sample.
$testarray=array();
$merge_array=array();
//receive parameter is Admin|Manager,User#Test
foreach ($roles as $value) {
if(preg_match("/[##%$|:\s,]+/",$value))
{
$testarray=preg_split("/[##%$|:\s,]+/",$value);
}
print_r(array_merge($merge_array,$testarray));
}
The print_r show this result.
Array ( [0] => Admin [1] => Manager ) Array ( [0] => User [1] => Test )
You just merge arrays, but don't assign results to any variable, proper code is:
//receive parameter is Admin|Manager,User#Test
foreach ($roles as $value) {
if(preg_match("/[##%$|:\s,]+/",$value))
{
$testarray=preg_split("/[##%$|:\s,]+/",$value);
}
// here you add $testarray values to
// `$merge_array` on each iteration
$merge_array = array_merge($merge_array,$testarray);
}
// print result array after loop
print_r($merge_array);
The Laravel framework has nothing to do with your issue. You're using PHP's standard functions.
The array_merge function doesn't modify the array you provide to it but provides the resulting array as its output. So you should assign array_merge's result to $merge_array.
Please try the following code:
$testarray = array();
$merge_array = array();
//receive parameter is Admin|Manager,User#Test
foreach ($roles as $value) {
if(preg_match("/[##%$|:\s,]+/",$value))
{
$testarray = preg_split("/[##%$|:\s,]+/",$value);
}
$merge_array = array_merge($merge_array, $testarray);
}
print_r($merge_array);
You seem to think wrong.
print_r(array_merge($merge_array,$testarray));
The above line is in "foreach" loop.
In that case, to get a merged result, you should do like the followings;
$merge_array = array_merge($merge_array,$testarray)
In your code, $merge_array remains empty, so you see the current result.

How can I rename some keys in a PHP array using another associative array?

Given a data array ...
$data_array = array (
"old_name_of_item" => "Item One!"
);
... and a rename array ...
$rename_array = array (
"old_name_of_item" => "new_name_of_item"
);
... I would like to produce an output like this:
Array
(
[new_name_of_item] => Item One!
)
I have written the following function, and while it works fine, I feel like I'm missing some features of PHP.
function rename_keys($array, $rename_array) {
foreach( $array as $original_key => $value) {
foreach( $rename_array as $key => $replace ) {
if ($original_key == $key) {
$array[$replace] = $value;
unset($array[$original_key]);
}
}
}
return $array;
}
Does PHP offer built-in functions to help with this common problem? Thanks!
You only have to go through the array once:
function rename_keys($array, $rename_array) {
foreach ( $rename_array as $original_key => $value ) {
if (isset($array[$original_key])) {
$array[$rename_array[$original_key]] = $array[$original_key];
unset($array[$original_key]);
}
}
}
This assumes, of course, that both arrays are correctly filled (unique values for the replacement keys).
Edit: only replace if a corresponding element exists in $rename_array.
Edit 2: only goes through $rename_array
Second time today. This one is easier:
$data_array = array_combine(
str_replace(array_keys($rename_array), $rename_array, array_keys($data_array)), $data_array);

foreach and multidimensional array

I have a multidimensional array and I want to create new variables for each array after apllying a function. I dont really know how to use the foreach with this kind of array. Here's my code so far:
$main_array = array
(
[first_array] => array
(
['first_array1'] => product1
['first_arrayN'] => productN
)
[nth_array] => Array
(
[nth_array1] => date1
[nth_arrayN] => dateN
)
)
function getresult($something){
## some code
};
foreach ($main_array as ["{$X_array}"]["{$key}"] => $value) {
$result["{$X_array}"]["{$key}"] = getresult($value);
echo $result["{$X_array}"]["{$key}"];
};
Any help would be appreciated!
foreach ($main_array as &$inner_array) {
foreach ($inner_array as &$value) {
$value = getresult($value);
echo $value;
}
}
unset($inner_array, $value);
Note the &, which makes the variable a reference and makes modifications reflect in the original array.
Note: The unset is recommended, since the references to the last values will stay around after the loops and may cause unexpected behavior if you're reusing the variables.
foreach($main_array AS $key=>$array){
foreach($array AS $newKey=>$val){
$array[$newKey] = getResult($val);
}
$main_array[$key] = $array;
}

Categories