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;
}
Related
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.
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);
For some reason I can not determine why empty array keys aren't being unset. Here is what I have...
PHP
<?php
$attachments = explode('|',$_POST['post_attachments']);
foreach($attachments as $k=>$v)
{
echo 'k = \''.$v."'\n";
if ($v=='')
{
unset($k);
}
}
print_r($attachments);die();
?>
Output
k = ''
k = 'secret_afound.gif'
k = 'secret_aunlocked.gif'
Array (
[0] =>
[1] => secret_afound.gif
[2] => secret_aunlocked.gif
)
You should do:
foreach ($attachments as $k=>$v) {
//...magic
unset($attachments[$k]);
}
You are only unsetting $k, not the element in attachments. Try unset($attachments[$k]);
I believe you should use unset($attachments[$k]);.
In this scenario I like to think of $k as a temporary variable. Even though you unset it you didn't alter $attachments in anyway.
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
}
}