I have two arrays.
I have a foreach loop which is iterating through one of these arrays ($items). For each value in this array, if a condition is not true, I would like to unset that same key, but from another, similar array ($list). (The two arrays are not identical, but the key will always be the same).
I am unsure how to go about this. The code I used below did not successfully unset the record from the first array.
Both arrays do have keys (IDs), with secondary data.
$list = array(
'id' => '2',
'id' => '3',
'id' => '4',
'id' => '5',
'id' => '6'
);
$items = array(
'id' => '2',
'id' => '3',
'id' => '4',
'id' => '5',
'id' => '6'
);
foreach ($items AS $key => $item)
{
if ($item['id'] != $setting)
{
unset($list[$key]);
}
}
What exactly are the keys in the arrays? Because, you cannot have every key in an array be the same. They overwrite each other. (Not sure if this is just for your example or not).
Anyway, using this code works, with tests to verify...
<?php
$list = array(
2,3,4,5,6
);
$items = array(
2,3,4,5,6
);
$set = 3;
foreach($list as $key => $val){
echo $key . " " . $val . "\n";
}
echo "\n -------------------- \n";
foreach($list as $key => $val){
if ($list[$key] != $set){
unset($items[$key]);
}
}
foreach($items as $key => $val){
echo $key . " " . $val . "\n";
}
?>
So, the actual working code to do what you are attempting to do is this:
$list = array(
2,3,4,5,6
);
$items= array(
2,3,4,5,6
);
$set = 3; //random variable to mock your $setting variable
foreach($list as $key => $val){
if ($list[$key] != $set){
unset($items[$key]);
}
}
This loops through $items and for every value that does not equal $setting, remove from list.
$setting = 3;
$list = array('2','3','4','5','6');
$items = array('2','3','4','5','6');
foreach ($items AS $key => $item)
{
if ($item != $setting)
{
unset($list[$key]);
}
}
print_r($list);
Output:
Array ( [1] => 3 )
So $list now only contains the value 3.
Related
I am learning php please help.
I am storing values in an array and then I am trying to get the id of another array checking the value in array like this:
$arr_folders = ['one', 'two', 'whatever'];
$id_one = '';
$id_two = '';
$id_whatever = '';
foreach ($tree as $key => $value) {
if($value['name'] == 'one'){//how to check dynamically?
$id_one = $value['id'];
}
if($value['name'] == 'two'){//how to check dynamically?
$id_two = $value['id'];
}
if($value['name'] == 'whatever'){//how to check dynamically?
$id_whatever = $value['id'];
}
}
echo $id_whatever;
How can I check the arrays values dynamically. I mean I want to check if the value exist in array then assign their id.
You need to use in_array to check whether the element is exist or not in another array, and if found you can create dynamic variable based on $value['name'] containing $value['id'] as required.
$tree = [
['id' => 1, 'name' => 'one'],
['id' => 2, 'name' => 'two'],
['id' => 3, 'name' => 'three']
];
$arr_folders = ['one', 'two', 'whatever'];
foreach ($tree as $key => $value) {
if (in_array($value['name'], $arr_folders)) {
${'id_'.$value['name']} = $value['id'];
}
}
echo $id_one;
Working Example: https://eval.in/596034
Note: make sure $value['name'] doesn't contain spaces or any other characters which aren't allowed to declare variable names.
Try using array search
For example:
<?php
$arr_folders = ['one', 'two', 'whatever'];
foreach ($tree as $key => $value) {
if (($key = array_search($arr_folders, $value)) !== false) {
return $arr_folders[$key];
}
}
echo $id_whatever;
If I understand the question, you're asking how you can check for the contents of one array (in this case, [one, two, whatever]) in the middle of looping through the other array without hardcoding it. If that's the case, I might try something like this:
$arr_folders = ['one', 'two', 'whatever'];
$id_folders = ['', '', '']
foreach ($tree as $key => $value) {
foreach ($arr_folders as $fkey => $fvalue) { // f for folder, in this case
if($value['name'] == $fvalue){
$id_folders[$fkey] = $value['id'];
}
}
}
echo $id_folders[2];
There may be other more elegant or time-effficient solutions, but I think this captures the dynamic nature you're looking for while mirroring the actual process of the previous code.
here is sample code :
<?php
$arr_folders = ['one', 'two', 'whatever'];
$tree= Array(Array('id' => 1,'name' => 'one'),
Array('id' => 2,'name' => 'large'),
Array('id' => 3,'name' => 'thumb'),
Array('id' => 4,'name' => 'two'),
Array('id' => 5,'name' => 'large'),
Array('id' => 6,'name' => 'thumb')
);
foreach ($tree as $key => $value) {
if(in_array($value['name'],$arr_folders)){
$searchedIds[] = $value['id'];
}
}
print_r($searchedIds);
?>
It's an interesting situation for getting the array key in multi-dimensional array.
I know how to get the array value by using foreach but how to get the key value and insert into database??
Here is my code:
//Array
$BookingInfo = array(
"115"=>array(
"date"=>array(
"15/12/2014"=>array(//need to get the date but not in here
array(
//need to get the date in here!!
"from"=>2,
"to"=>5,
"user"=>"Ella",
"userid"=>"b2111"
),
array(
"from"=>5,
"to"=>7,
"user"=>"Johnson",
"userid"=>"a2413"
)
),
"16/12/2014"=>array(
array(
"from"=>4,
"to"=>8,
"user"=>"Peter",
"userid"=>"g531"
)
),
"17/12/2014"=>array(
array(
"from"=>1,
"to"=>3,
"user"=>"Chris",
"userid"=>"h024"
),
array(
"from"=>3,
"to"=>6,
"user"=>"Jennifer",
"userid"=>"f314"
)
),
"20/12/2014"=>array(
array(
"from"=>1,
"to"=>5,
"user"=>"Raymond",
"username"=>"r362"
)
),
"21/12/2014"=>array(
array(
"from"=>1,
"to"=>6,
"user"=>"Amy",
"username"=>"a754"
)
),
"23/08/2014"=>array(
array(
"from"=>2,
"to"=>4,
"user"=>"Amy",
"userid"=>"m432"
)
)
)
)
);
The foreach code:
foreach($BookingInfo as $roomNumber => $value){
foreach($value as $id => $val){
foreach($val as $bookDate => $array){
foreach($array as $key => $detail){
foreach($detail as $period =>$info){
//get the $bookDate here
//if I get the "$bookDate" here, it shows the result with repeating 3 times, how can I solve it??
}
}
}
}
}
And I want to get the "15/12/2014" 2 times because of two members' booking, and the "16/12/2014" 1 times, what is the method to do it? Thanks for help.
It's probably easiest to just add the bookDate to the detail array, in the second innermost loop:
foreach($BookingInfo as $roomNumber => $value){
foreach($value as $id => $val){
foreach($val as $bookDate => $array){
foreach($array as $key => $detail){
$detail['bookDate'] = $bookDate;
foreach($detail as $detailkey =>$detailval){
print "$detailkey => $detailval\n";
}
print "***\n";
}
}
}
}
(Just make sure that whatever key you use isn't one that might be in the details array already or you might cause some confusion).
See http://codepad.org/oQT3cmo8 for output
Have an array for a ranking script.
Some times the key will be the same. They are numeric.
When the sort is ran, only non-like values are echoed.
Can't figure out the fix.
$list = array( $value1 => 'text', $value2 => 'text', $value3 => 'text');
krsort($list);
foreach ($list as $key => $frame) {
echo $frame;
}
If you assign two values to the same key in an array, the first value will be overridden by the second. You'll therefore end up with only one value for that key in the array.
To resolve this, I'd suggest to change your array structure like this:
<?php
$list = array( $key1 => array($key1member1, $key2member2),
$key2 => array($key2member1),
$key3 => array($key3member1, $key3member2, $key3member3) );
krsort($list);
foreach ($list as $key => $frames) {
foreach ($frames => $frame) {
echo $frame;
}
}
?>
Going by what you wrote in the comments to this question and my other answer, I'd recommend to switch keys and values.
<?php
$list = array( "frame1" => 4, "frame2" => 2, "frame3" => 99, "frame4" => 42 );
arsort($list);
foreach ($list as $frame => $ranking) {
echo $frame;
}
?>
I was wondering when working with multimedional arrays, if a certain key is the same, is there a way to combine the contents of other keys into its own array if a certain key is the same?
Something like this:
// name is the same in both arrays
array(
array(
'name' => 'Pepsi',
'store' => 'Over here',
'number' => '1234567'
),
array(
'name' => 'Pepsi',
'store' => 'Over here',
'number' => '5556734'
)
)
into something like this
array(
array(
'name' => 'Pepsi',
'store' => array('Over here', 'Over here'),
'number' => array('1234567', '5556734')
)
)
The defining key is checking if the name element is the same for the other arrays.
You can try a function like this.
function mergeByKey($array,$key){
$tmp_array = array();
foreach ( $array as $k => $row ) {
$merged = false;
foreach ($tmp_array as $k2 => $tmp_row){
if ($row[$key] == $tmp_row[$key]){
foreach ( $row as $k3 => $value ) {
if ($k3 == $key) continue;
$tmp_array[$k2][$k3][] = $value;
$merged = true;
}
}
if ($merged) break;
}
if (!$merged) {
$new_row = array();
foreach ( $row as $k4 => $value ) {
if ($k4 == $key) $new_row[$k4] = $value;
else $new_row[$k4] = array($value);
}
$tmp_array[] = $new_row;
}
}
foreach ( $tmp_array as $t => $row ) {
foreach ( $row as $t2 => $value ) {
if ( count($value) == 1 && $t2 != $key ) $tmp_array[$t][$t2] = $value[0];
}
}
return $tmp_array;
}
passing the array as first parameter and the key as second one.
I'm referencing to your array structure
edited: missed a piece
edited2: if resultin array contains elements with one string, it returns a string and not a array with one element
demo
This function uses a given field name as the grouping identifier and turns all other fields into arrays.
Note that single occurrences of your field name will yield arrays with a single element for the other fields. I wasn't sure whether that's a desirable trait, but just making sure you know ;-)
$arr = array(
array(
'name' => 'Pepsi',
'store' => 'Over here',
'number' => '1234567'
),
array(
'name' => 'Pepsi',
'store' => 'Over here',
'number' => '5556734'
)
);
function mergeArray($array, $column)
{
$res = array();
foreach ($array as $item) {
foreach ($item as $key => $value) {
if ($key === $column) {
$res[$column][$key] = $value;
} else {
$res[$column][$key][] = $value;
}
}
}
return array_values($res);
}
print_r(mergeArray($arr, 'name'));
Demo
Thanks to Gianni Lovece for her answer but I was able to develop a much simpler solution based on this problem. Just plug in the $result_arr to browse through and the $key you want to use as basis and it immediately outputs a multidimensional array with non-repeating values for repeating elements (see example below).
function multiarray_merge($result_arr, $key){
foreach($result_arr as $val){
$item = $val[$key];
foreach($val as $k=>$v){
$arr[$item][$k][] = $v;
}
}
// Combine unique entries into a single array
// and non-unique entries into a single element
foreach($arr as $key=>$val){
foreach($val as $k=>$v){
$field = array_unique($v);
if(count($field) == 1){
$field = array_values($field);
$field = $field[0];
$arr[$key][$k] = $field;
} else {
$arr[$key][$k] = $field;
}
}
}
return $arr;
}
For example, in the sample array for this question, running multiarray_merge($mysample, 'name') returns
array(
'Pepsi' => array(
'name' => 'Pepsi',
'store' => 'Over here', // String: Not an array since values are not unique
'number' => array('1234567', '5556734') // Array: Saved as array since values are unique
)
);
In an array such as the one below, how could I rename "fee_id" to "id"?
Array
(
[0] => Array
(
[fee_id] => 15
[fee_amount] => 308.5
[year] => 2009
)
[1] => Array
(
[fee_id] => 14
[fee_amount] => 308.5
[year] => 2009
)
)
foreach ( $array as $k=>$v )
{
$array[$k] ['id'] = $array[$k] ['fee_id'];
unset($array[$k]['fee_id']);
}
This should work
You could use array_map() to do it.
$myarray = array_map(function($tag) {
return array(
'id' => $tag['fee_id'],
'fee_amount' => $tag['fee_amount'],
'year' => $tag['year']
); }, $myarray);
$arrayNum = count($theArray);
for( $i = 0 ; $i < $arrayNum ; $i++ )
{
$fee_id_value = $theArray[$i]['fee_id'];
unset($theArray[$i]['fee_id']);
$theArray[$i]['id'] = $fee_id_value;
}
This should work.
Copy the current 'fee_id' value to a new key named 'id' and unset the previous key?
foreach ($array as $arr)
{
$arr['id'] = $arr['fee_id'];
unset($arr['fee_id']);
}
There is no function builtin doing such thin afaik.
This is the working solution, i tested it.
foreach ($myArray as &$arr) {
$arr['id'] = $arr['fee_id'];
unset($arr['fee_id']);
}
The snippet below will rename an associative array key while preserving order (sometimes... we must). You can substitute the new key's $value if you need to wholly replace an item.
$old_key = "key_to_replace";
$new_key = "my_new_key";
$intermediate_array = array();
while (list($key, $value) = each($original_array)) {
if ($key == $old_key) {
$intermediate_array[$new_key] = $value;
}
else {
$intermediate_array[$key] = $value;
}
}
$original_array = $intermediate_array;
Converted 0->feild0, 1->field1,2->field2....
This is just one example in which i get comma separated value in string and convert it into multidimensional array and then using foreach loop i changed key value of array
<?php
$str = "abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu
abc,def,ghi,jkl,mno,pqr,stu;
echo '<pre>';
$arr1 = explode("\n", $str); // this will create multidimensional array from upper string
//print_r($arr1);
foreach ($arr1 as $key => $value) {
$arr2[] = explode(",", $value);
foreach ($arr2 as $key1 => $value1) {
$i =0;
foreach ($value1 as $key2 => $value2) {
$key3 = 'field'.$i;
$i++;
$value1[$key3] = $value2;
unset($value1[$key2]);
}
}
$arr3[] = $value1;
}
print_r($arr3);
?>
I wrote a function to do it using objects or arrays (single or multidimensional) see at https://github.com/joaorito/php_RenameKeys.
Bellow is a simple example, you can use a json feature combine with replace to do it.
// Your original array (single or multi)
$original = array(
'DataHora' => date('YmdHis'),
'Produto' => 'Produto 1',
'Preco' => 10.00,
'Quant' => 2);
// Your map of key to change
$map = array(
'DataHora' => 'Date',
'Produto' => 'Product',
'Preco' => 'Price',
'Quant' => 'Amount');
$temp_array = json_encode($original);
foreach ($map AS $k=>$v) {
$temp_array = str_ireplace('"'.$k.'":','"'.$v.'":', $temp);
}
$new_array = json_decode($temp, $array);
Multidimentional array key can be changed dynamically by following function:
function change_key(array $arr, $keySetOrCallBack = [])
{
$newArr = [];
foreach ($arr as $k => $v) {
if (is_callable($keySetOrCallBack)) {
$key = call_user_func_array($keySetOrCallBack, [$k, $v]);
} else {
$key = $keySetOrCallBack[$k] ?? $k;
}
$newArr[$key] = is_array($v) ? array_change_key($v, $keySetOrCallBack) : $v;
}
return $newArr;
}
Sample Example:
$sampleArray = [
'hello' => 'world',
'nested' => ['hello' => 'John']
];
//Change by difined key set
$outputArray = change_key($sampleArray, ['hello' => 'hi']);
//Output Array: ['hi' => 'world', 'nested' => ['hi' => 'John']];
//Change by callback
$outputArray = change_key($sampleArray, function($key, $value) {
return ucwords(key);
});
//Output Array: ['Hello' => 'world', 'Nested' => ['Hello' => 'John']];
I have been trying to solve this issue for a couple hours using recursive functions, but finally I realized that we don't need recursion at all. Below is my approach.
$search = array('key1','key2','key3');
$replace = array('newkey1','newkey2','newkey3');
$resArray = str_replace($search,$replace,json_encode($array));
$res = json_decode($resArray);
On this way we can avoid loop and recursion.
Hope It helps.