Say you have the array .
$arr = array('foo' => 'bar, 'wang' => 'chung', 'ying' => 'yang');
Now I want to loop through another array (var = $terms) to get values using foreach. If the value is any of the keys listed in $arr, I want to replace it with the value listed in $arr.
I've tried this ...
foreach($terms as $term => $arr) {
echo $term[$arr];
}
This doesn't work ... and I'm pretty stumped beyond that point. Reading through the manual on foreach ... I felt like this was on the right path - but think I'm needing a nudge in another direction.
Thoughts?
You can use array_key_exists() function for verifying whether key exists in another array or not If found then replace that with existing once. You can refer below answer,
$arr = array('foo' => 'bar', 'wang' => 'chung', 'ying' => 'yang');
$res = [];
foreach($terms as $term => $arr1) {
if( array_key_exists( $term, $arr ) ) {
$res[$term] = $arr[$term];
} else {
$res[$term] = $arr1;
}
}
echo '<pre>'; print_r($res);
I hope this will resolve your problem.
Related
I have an associative array
array(
'item_name1' => 'PCC',
'item_name2' => 'ext',
'item_number1' => '060716113223-13555',
'item_number2' => '49101220160607-25222)',
)
What i Want to do is catch all the array keys where the key name has similarities
for example
i want to echo out item_name (it should get both item_name1 & item_name2) but i require it in a loop (foreach/for) so that i can send within the loop the details to my database for each set of values
Thanks For the help
Use the funtion array_keys
$allKeys = array_keys($yourArray);
$amountKeys = count($allKeys);
Unless you do not provide more code this will give you all the keys of $yourArray
Reference - array_keys
To get all the similar keys you can use this function similar-text()
Since I do not know how "similar" a key can be I would suggest you to test out different values and find a degree that matches your expectations.
Your data model seems to use numeric suffixes as a replacement for arrays so I'll assume that key name has similarities is an overestimated problem statement and you merely want to fix that.
The obvious tool is regular expressions:
$original_data = array(
'item_name1' => 'PCC',
'item_name2' => 'ext',
'item_number1' => '060716113223-13555',
'item_number2' => '49101220160607-25222)',
);
$redacted_data = array();
foreach ($original_data as $key => $row) {
if (preg_match('/^(.+)(\d+)$/u', $key, $matches)) {
$redacted_data[$matches[1]][$matches[2]] = $row;
} else {
$redacted_data[$key][] = $row;
}
}
var_dump($redacted_data);
It should be easy to tweak for your exact needs.
I can't figure out what the i require it in a loop (foreach/for) requirement means but you can loop the resulting array as any other array:
foreach ($redacted_data as $k => $v) {
foreach ($v as $kk => $vv) {
printf("(%s,%s) = %s\n", $k, $kk, $vv);
}
}
<?php
$items=[];
$itemsNumbers=[];
foreach($itemarr as $key=> $val)
{
$itempos = strpos("item_name", $key);
if ($pos !== false)
$items[]=$val;
$numberpos = strpos("item_number", $key);
if ($numberpos !== false)
$itemsNumbers[]=$val;
}
?>
Note: here $itemarr is your input array
$items you will get list of item names and $itemsNumbers you will get list of itemsNumbers
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);
I have an array of dictionnaries like:
$arr = array(
array(
'id' => '1',
'name' => 'machin',
),
array(
'id' => '2',
'name' => 'chouette',
),
);
How can I find the name of the array containing the id 2 (chouette) ?
Am I forced to reindex the array ?
Thank you all, aparently I'm forced to loop through the array (what I wanted to avoid), I thought that it were some lookup fonctions like Python. So I think I'll reindex with id.
Just find the index of array that contains the id you want to find.
SO has enough questions and answers on this topic available.
Assuming you have a big array with lots of data in your real application, it might be too slow (for your taste). In this case, you indeed need to modify the structure of your arrays, so you can look it up faster, e.g. by using the id as an index for the name (if you are only interested in the name).
As a for loop would be the best way to do this, I would suggest changing you array so that the id is the arrays index. For example:
$arr = array(
1 => 'machin',
2 => 'chouette',
);
This way you could just get the name for calling $arr[2]. No looping and keeping your program running in linear time.
$name;
foreach ($arr as $value){
if ( $value['id'] == 2 ){
$name = $value['name'];
break;
}
}
I would say that it might be very helpful to reindex the information. If the ID is unique try something like this:
$newarr = array();
for($i = 0;$i < count($arr);$i++){ $newarr[$arr[$i]['id']] = $arr[$i]['name']; }
The result would be:
$newarr = array('1'=>'machin','2'=>'chouette');
Then you can go trough the array with "foreach" like this:
foreach($newarr as $key => $value){
if($value == "machin"){
return $key;
}
}
But of course the same would work with your old array:
foreach($arr as $item){
if($item['name'] == "machin"){
return $item['id'];
}
}
It depends on what you are planning to do with the array ;-)
array_key_exist() is the function to check for keys. foreach will help you get down in the multidimensional array. This function will help you get the name element of an array and let you specify a different id value.
function findKey($bigArray, $idxVal) {
foreach($bigArray as $array) {
if(array_key_exists('id', $array) && $array['id'] == $idxVal) {
return $array['name'];
}
}
return false;
}
//Supply your array for $arr
print(findKey($arr, '2')); //"chouette"
It's a bit crude, but this would get you the name...
$name = false;
foreach($arr as $v) {
if($v['id'] == '2') {
$name = $v['name'];
break;
}
}
echo $name;
So no, you are not forced to reindex the array, but it would make things easier.
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;
}
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
}
}