Setting a multi-dimensional array value - php

I have an array that looks like...
$arr = array(
array(
"server_name" => "server_a",
"server_number" => "1",
"server_status" => "OPEN"
),
array(
"server_name" => "server_b",
"server_number" => "2",
"server_status" => "CLOSED"
)
);
I am trying to set the index value of "server_status" in the following way
foreach($arr as $a){
$a['server_status'] = "STATUS_".$a['server_status'];
}
This does not seem to be the correct way to set an array value as nothing seems to be happening, what would be the correct way to perform this task?

You need to iterate by reference:
foreach($arr as &$a) {
$a['server_status'] = ...;
}
(The only difference from your code is the & before $a in foreach.)
Just don't forget to unset the reference after iterating:
unset($a);
Else, writing to this variable later in the code would override the last element of the array.
See foreach documentation.

You need to foreach by reference, like this:
foreach($arr as &$a){
$a['server_status'] = "STATUS_".$a['server_status'];
}
Otherwise it does not modify the item of the current iteration - its a copy.

Related

PHP rename key in Associative array

I've been searching through the articles on SO for this question and tried many of the solutions in my own code but it's not seeming to work.
I have the following array
$array[] = array("Order_no"=>$order_id,
"Customer"=>$customer_id,
"Product"=>$code_po,
"Product_description"=>$code_description,
"Position"=>$pos,
"Qty"=>$item_qty
);
I am looking to replace the "Order_no" key with a variable from a database query, lets assume in this case the variable is "new_name"
$new = "new_name";
$array[$new]=$array["Order_no"];
unset($array["Order_no"]);
print_r($array);
in the print_r statement I am getting the new_name coming through as the correct order number, but I am still seeing "Order_no" there also, which I shouldn't be seeing anymore.
Thanks.
This is your array:
Array
(
[0] => Array
(
[Customer] => 2
[Product] => 99
[Order_no] => 12345
)
)
One way to do it:
<?php
$arr[] = [
"Order_no" => 12345,
"Customer" => 00002,
"Product"=> 99
];
$i_arr = $arr[0];
$i_arr["new_name"] = $i_arr["Order_no"];
unset($i_arr["Order_no"]);
$arr[0] = $i_arr;
print_r($arr);
Another way:
<?php
$arr[] = [
"Order_no" => 12345,
"Customer" => 00002,
"Product"=> 99
];
$arr[0]["new_name"] = $arr[0]["Order_no"];
unset($arr[0]["Order_no"]);
print_r($arr);
To flatten your array out at any time:
<?php
$arr = $arr[0];
print_r($arr);
You are using extra level of array (by doing $array[] = ...).
You should do it with [0] as first index as:
$array[0][$new]=$array[0]["Order_no"];
unset($array[0]["Order_no"]);
Live example: 3v4l
Another option is get ride of this extra level and init the array as:
$array = array("Order_no"=>$order_id, ...
As $array is also an array, you have to use index:
$array[0][$new]=$array[0]["Order_no"];
unset($array[0]["Order_no"]);
The other answers will work for the first time you add to the array, but they will always work on the first item in the array. Once you add another it will not work, so get the current key:
$array[key($array)][$new] = $array[key($array)]["Order_no"];
unset($array[key($array)]["Order_no"]);
If you want the first one, then call reset($array); first.
Change your variable to
$array=array("Order_no"=>$order_id,"Customer"=>$customer_id,"Product"=>$code_po,"Product_description"=>$code_description,"Position"=>$pos,"Qty"=>$item_qty);
or change your code to
$new = "new_name";
$array[0][$new]=$array[0]["Order_no"];
unset($array["Order_no"]);
print_r($array);
Just be careful this would change the order of the array

Get array element by value in similar way like getting by $key

Is there a possibility in PHP to get an array element by it's value. What I wan't to do is to update an element without knowing the key but nowing it's value:
$translations = array(
"en" => 123,
"de" => 456,
"es" => 789,
"fr" => 901
);
i know that what i wan't to do can be done with an foreach loop:
foreach($translations as $lang=>$id):
if($id == 123) $translations[$lang] = 0;
endforeach;
But is there any possibility to avoid this loop and to automatically set it?
You are looking for array_search():
if(false!==($key = array_search(123, $translations)))
{
$translations[$key] = 0;
}
-be aware that value can be non-unique, so array_search() will find only first key. If you need all of them, you'll have to either iterate through array with foreach or use something like array_walk()
You should use this :
$translations[array_search('123', $translations)] = 0;
Edit: use the solution proposed by Alma Do Mundo, he is right about checking the return value
You can do it in this way also.
Use array_keys function with search_values parameter. It will give you the array of keys which are having these values. Then you can update the original array based on the new array.
It will take care of all the duplicate values also.
$translations = array(
"en" => 123,
"de" => 456,
"es" => 789,
"fr" => 901,
"it" => 123
);
$arr=array_keys($translations,$seach_value);
if(count($arr)){
foreach($arr as $key => $value){
$translations[$value]=$new_value;
}
}

php extract sub array with specific key

if i have the following array:
array(
'var1' => 123,
'var2' => 234,
'var3' => 345
);
I would like to extract specific parts of this to build a new array i.e. var1 and var3.
The result i would be looking for is:
array(
'var1' => 123,
'var3' => 345
);
The example posted is very stripped down, in reality the array has a much larger number of keys and I am looking to extract a larger number of key and also some keys may or may not be present.
Is there a built in php function to do this?
Edit:
The keys to be extracted will be hardcoded as an array in the class i..e $this->keysToExtract
$result = array_intersect_key($yourarray,array_flip(array('var1','var3')));
So, with your edit:
$result = array_intersect_key($yourarray,array_flip($this->keysToExtract));
You don't need a built in function to do this, try this :
$this->keysToExtract = array('var1', 'var3'); // The keys you wish to transfer to the new array
// For each record in your initial array
foreach ($firstArray as $key => $value)
{
// If the key (ex : 'var1') is part of the desired keys
if (in_array($key, $this->keysToExtract)
{
$finalArray[$key] = $value; // Add to the new array
}
}
var_dump($finalArray);
Note that this is most likely the most efficient way to do this.

PHP take array key and value from beginning and put at end

I have a PHP array that has literal_key => value. I need to shift the key and value off the beginning of the array and stick it at the end (keeping the key also).
I've tried:
$f = array_shift($fields);
array_push($fields, $f);
but this loses the key value.
Ex:
$fields = array ("hey" => "there", "how are" => "you");
// run above
this yields:
$fields = array ("how are" => "you", "0" => "there");
(I need to keep "hey" and not have 0) any ideas?
As far as I can tell, you can't add an associative value to an array with array_push(), nor get the key with array_shift(). (same goes for pop/push). A quick hack could be:
$fields = array( "key0" => "value0", "key1" => "value1");
//Get the first key
reset($fields);
$first_key = key($fields);
$first_value = $fields[$first_key];
unset($fields[$first_key]);
$fields[$first_key] = $first_value;
See it work here. Some source code taken from https://stackoverflow.com/a/1028677/1216976
You could just take the 0th key $key using array_keys, then set $value using array_shift, then set $fields[$key] = $value.
Or you could do something fancy like
array_merge( array_slice($fields, 1, NULL, true),
array_slice($fields, 0, 1, true) );
which is untested but has the right idea.

Finding a value inside a nested array having only a string with the keys

I have one array that contains some settings that looks like basically like this:
$defaults = array(
'variable' => 'value',
'thearray' => array(
'foo' => 'bar'
'myvar' => array('morevars' => 'morevalues');
);
);
On another file, i get a string with the first level key and it's childs to check if there is a value attached to it. Using the array above, i'd get something like this:
$option = "thearray['myvar']['morevars']";
I need to keep this string with a similar format to the above because I also need to pass it to another function that saves to a database and having it in an array's format comes in handy.
My question is, having the array and the string above, how can i check for both, existance and value of the given key inside the array? array_key_exists doesn't seem to work below the first level.
You could use a simple function to parse your key-string and examine the array like:
function array_deep_exists($array, $key)
{
$keys = preg_split("/'\\]|\\['/", $key, NULL, PREG_SPLIT_NO_EMPTY);
foreach ($keys as $key)
{
if ( ! array_key_exists($key, $array))
{
return false;
}
$array = $array[$key];
}
return true;
}
// Example usage
$defaults = array(
'variable' => 'value',
'thearray' => array(
'foo' => 'bar',
'myvar' => array('morevars' => 'morevalues')
)
);
$option = "thearray['myvar']['morevars']";
$exists = array_deep_exists($defaults, $option);
var_dump($exists); // bool(true)
Finally, to get the value (if it exists) return $array where the above returns true.
Note that if your array might contain false, then when returning the value you'll have to be careful to differentiate no-matching-value from a successful false value.
You need to eval this code, and use isset function in an eval string, and don't forget to add $ character in right place before code eval
example:
eval("echo isset(\$defaults['varname']['varname2']);")
this will echo 0 or 1 (false or true) You can do anything in eval, like a php source

Categories