I got values of column A and B from Excel by below php code
for($i=1;$i<=$arrayCount;$i++)
{
$col_A = array(trim($allDataInSheet [$i]["A"]));
$col_B =array(trim($allDataInSheet [$i]["B"]));
}
If 'A' has 44 variable names and 'B' has 44 values.
In this scenario,How can I assign the values of 'B' to the variable names of 'A'
Please help me to solve this
Arrays in PHP can take on two different key-types and they can mix and match. Indexed by number and indexed by string. And an array can contain any value, including an array of values. This means that you can create an array that uses the names in Array A as the keys and the values in Array B as the values for those keys.
$columns = [];
// Arrays start at 0, but since these came from excel 0 is the column header.
// You want to stop 1 entry before the count of your array. Since arrays are 0 indexed, the array count is 1 larger than the last index.
for($i=1;$i<=$arrayCount-1;$i++)
{
$a = trim($allDataInSheet [$i]["A"]);
$b = trim($allDataInSheet [$i]["B"]);
// You don't need to specify the Array constructor anymore.
// You can just use brackets to create a new array.
// Not sure if you still want these, but I left them for you.
$col_A = [$a];
$col_B = [$b];
// Assign the values of B to columns in A
if(!isset($columns[$a]) {
$columns[$a] = $b;
} else {
// Debugging message - Tried to set two values to the same name.
}
}
// Do stuff with $columns
// $columns["a"] == "b"
Above, you can see that since $allDataInSheet[$i]["A"] is the string we want, we can just use that value as our key and its matching entry in B as the value for that key.
Notice how we don't let a value get added to the array if we already have that name set. If you want $columns[$a] to be an array of values, you can change it to look like this:
if(!isset($columns[$a]){
// If we don't have an entry for $columns[$a] create an array here to hold the values for possible $b's.
$columns[$a] = [];
}
// Add $b to the $columns[$a] array.
$columns[$a][] = $b;
That will treat the $columns array as an array of arrays. Meaning that each position can hold multiple values. So, we turn it into an array and just add the $b value to that position. If we come across that $a value again, we'll see that we already have that position set and we just use the array that's already there.
Notice - we do an isset check instead of an empty check because if 'b' was actually " " or false or 0 or for some strange reason, $columns[$a] doesn't change from an empty array to an array with something in it, than we don't want to erase the value that's already there.
Good Luck!
Related
Lets say I have an array looking like this:
$sql = array("name"=>"Peter", "active"=>1 , "age"=>30)
and a loop looking like this:
for($i=0;$i<count($sql);$i++){
$value[$i] = ($sql[$i]);
echo $value[$i];
}
I want the loop to iterate through the array and assign each value to a new variable.
In this code i tried to make it store the values in:
value1
value2
value3
But sadly this doesnt work, thus I am here seeking help.
Or is it a problem that i got an associative array instead of a numeric one?
I dont want to use this loop on this array only but on other arrays with different keys and length aswell.
Edit: I think I may have not wrote it cleary enough to tell you what i want to achieve:
I want to have three string values at the end of the loop not stored in an array:
Variable1 should contain "Peter"
Variable2 should contain "1"
Variable3 should contain "30"
Plus I want this loop to be dynamic, not only accepting this specific array but if I were to give it an array with 100 Values, I would want to have 100 different variables in which the values are stored.
Sorry for not being clear enough, I am still new at stackoverflow.
Going by your condition, assign each value to a new variable, I think what you want would be to use Variable variables. Here is an example:
<?php
$sql = array("name"=>"Peter", "active"=>1 , "age"=>30);
$count = 1;
foreach ($sql as $value) {
$x = 'value'.$count;
$$x = $value; //here's the usage of Variable variables
$count++;
}
echo $value1.'<br/>';
echo $value2.'<br/>';
echo $value3.'<br/>';
I went to your sample variables ($value1, $value2, etc.). I also changed your loop to foreach to easily loop the array. And I also added a $count that will serve as the number of the $value variable.
The $count wouldn't be necessary if your index are numeric, but since its an associative array, something like this is needed to differentiate the variables created
A brief explanation as requested:
$x contains the name of the variable you want to create (in this case, value1), then when you add another $ to $x (which becomes $$x), you are assigning value to the current value of $x (this equals to $value1='Peter')
To dynamically define a variable use $$. Demo
$sql = array("name"=>"Peter", "active"=>1 , "age"=>30);
$index = 1;
foreach($sql as $value){
${"value" . $index++} = $value;
}
I've a multidimensional array of some arrays, in which the first values are ordered and included in a specific range.
Example:
A1=[[0,a],[3,b],[5,c],[6,a],[9,c]]
in which A1[i][0] are in range (0,10)
How can I obtain an array where, if the first value
(A1[i][0]) isn't a value present in the first array, e.g.
A1[i][0]==2
I insert an array with that value in the right position, with a specified second value (example A)?
Example of output i want:
A1=[[0,a],[1,A],[2,A],[3,b],[4,A],[5,c],[6,a],[7,A],[8,A],[9,c]]
This will help
$A1 = [[0,'a'],[3,'b'],[5,'c'],[6,'a'],[9,'c']];
foreach($A1 as $A2) $A3[] = $A2[0];//make a new array contain keys of the first array.
for($i=0;$i<=9;$i++){
if(!in_array($i, $A3)){
$A1[] = [$i, 'A']; //check if the key not exist, make a new array with key who does not exist.
}
}
asort($A1);//sort the new element inside the array
print_r($A1);
output is,
[[0,a],[1,A],[2,A],[3,b],[4,A],[5,c],[6,a],[7,A],[8,A],[9,c]]
Thank you for taking your time to look at this question.
I have a database entry that contains a serialized array (of multiple arrays). It might look like this:
Array 1
a:2:{
i:0;a:3:{s:11:"search_type";s:6:"owners";s:11:"search_text";s:4:"test";s:11:"search_name";s:4:"test";}
i:1;a:5:{s:8:"t_rating";s:3:"Yes";s:9:"t_ranking";s:3:"Yes";s:11:"search_type";s:8:"products";s:11:"search_text";s:5:"test2";s:11:"search_name";s:5:"test2";}
}
Then, I have another serialized array being passed that might look like this:
Array 2
a:2:{s:11:"search_type";s:6:"owners";s:11:"search_text";s:4:"test";}
Conditions
Array 1 can have any number of nested arrays (my example shows 2).
Array 2 is passed from a selector; which should loop Array 1 and remove it's associated nested array.
These arrays are being compared using PHP.
The Problem
The issue is that each array in Array 1 needs to first remove the "search_name" array key before making the comparison.
The "search_name" key from Array 1 should never be used for comparison. When the "search_name" key is removed; a valid comparison of the serialized arrays can then be made.
But, when this gets updated to the db; the non-removed arrays should still contain the "search_name" key. It only needs to be removed for comparison; then it's full array should be removed from Array 1.
My (Broken) Code
Here is what I currently have:
$search_array = unserialize($_POST['search_array']); // Serialized Array 2
$bm_adv_search = $query_adv_search[0]->bm_adv_search; // Serialized Array 1
$unser_array = unserialize($bm_adv_search); // Unserialize Array 1
// Unset search_name from each array in Array 1
foreach($unser_array as $key => $value) {
unset($unser_array[$key]['search_name']); // THIS IS THE PROBLEM AREA
}
// Unset Array 2 from Array 1
if(in_array($search_array, $unser_array)) {
if(($key = array_search($search_array, $unser_array)) !== false) {
unset($unser_array[$key]);
}
}
// Re-Serialize Array 1
$reser_array = serialize($unser_array);
// Update db with Array 1
.....
So when I update Array 1 to the db; the name field has been removed from all nested arrays, which when updated, excludes the "search_name".
I need the "search_name" to stay in each array from Array 1 when updated. I just need to remove it for comparison purposes... and then remove the nested array from Array 1.
The Idea
Basically, I am storing user saved bookmarks. When a user bookmarks an item; a serialized array gets added to Array 1. A user is prompted to enter a "Name" for the search bookmark; hence the "search_name" field.
When a user clicks to remove a bookmark; the "search_name" key is not available in the comparison array (Array 2). Array 1 should be looped for Array 2's existence (minus the "search_name" key)... and the entire matched array (including "search_name") should be unset.
Again, thank you for any time on this question. I really appreciate any assistance.
UPDATE
Got it working. Thanks Mikel!!
Here is the updated code:
$search_array = unserialize($_POST['search_array']); // Serialized Array 2
$bm_adv_search = $query_adv_search[0]->bm_adv_search; // Serialized Array 1
$unser_array = unserialize($bm_adv_search); // Unserialize Array 1
// Clone Array 1
$compare_array = $unser_array;
// Unset search_name from each array in cloned Array 1
foreach($compare_array as $key => $value) {
unset($compare_array[$key]['search_name']);
}
// Unset Array 2 from Array 1
if(in_array($search_array, $compare_array)) {
if(($key = array_search($search_array, $compare_array)) !== false) {
unset($unser_array[$key]);
}
}
// Re-Serialize Array 1
$reser_array = serialize($unser_array);
// Update db with Array 1
.....
Copy your "Array 1" to a temporary array for comparison, but do any true modifications to the main $unser_array.
Could be as simple as $compar_array = $unser_array and then modifying a few of the vars throughout the code.
You can then compare the two by array key, as they keys will be identical in the arrays. (you just created this copy)
Lemme know if you need any help!
How can I tell if array element, in foreach loop, has a key?
Some code:
function test($p_arr){
foreach ($p_arr as $key => $value){
// detect here if key 'came with the array' or not
}
}
$arr1['a'] = 10;
$arr2[] = 10;
$arr3[2] = 10;
test($arr1); // yes
test($arr2); // no
test($arr3); // yes
edit #1
I am aware that $arr2 also as an automated index-key. I need to know if it is automated or not.
edit #2
My use of it is simple.
In the function, I create a new array and use the $key as the new $key, if it was provided by the function call. or the $value as the new $key, if it was omitted in the function call.
I know that I can just force the use of key to each element, but in some parts of the code, the data structure itself is very dynamic* - and i'm trying to stay flexible as much as possible.
*code that create other code, that create ... and so on.
There is no difference between explicit keys and implicit keys generated via []. The [] doesn't mean "give this element no key", it means "use the next key for this element".
Every element has a key
$arr1['a'] = 10; // key is the string 'a'
$arr2[] = 10; // key is will be the integer zero
$arr3[2] = 10; // key is the integer 2
Edit
Perhaps it would be good to understand why you wish to know if the index is automated or not? It seems odd.
Every array created has to have a key, whether it's a integer or string as the key or index, without no index the PHP would have no way to interpret or even pull information from the array it's self.
$Var = array ("String","anotherstring","sdfhs","dlj");
the above array will automatically be generated with a numeric index starting from 0.
$Array = array();
$Array[] = "This is a string";
The above will push information into the array, as there has been no index or key specified. It will automatically be assigned with the closest numeric value to 0, which does not already exist in the array.
$Array = array();
$Array['key'] = "This is another string";
The above will push information into the array also, but as we have specified an index with a string representation rather an automatically assigned value.
So the answer to your question, if i'm reading this Correctly.
If your referring to check if the array values are specified by PHP/The Code prior to reading the array. There is no soundproof method, as everything would need to be assigned to the array before it has data. further more, if your only adding elements to the array with a string key, then yes. It is possible.
If your relying on automatically generated numeric values, or assigning your own numeric values. it's impossible to tell if PHP has assigned this automatically, or you have specified.
I have a multi-dimensional array of databases, which was generated from my server:
// place db tables into array
$da_db = array(
'test' => array(
// test.users
'users' => array('fname','lname','info'),
// test.webref_rss_details
'webref_rss_details' => array('id','title','link','description','language','image_title','image_link','item_desc','image_width','image_height','image_url','man_Edit','webmaster','copyright','pubDate','lastBuild','category','generator','docs','cloud','ttl','rating','textInput','skipHours','skipDays'),
// test.webref_rss_items
'webref_rss_items' => array('id','title','description','link','guid','pubDate','author','category','comments','enclosure','source','chan_id')
),
'db_danaldo' => array(
//code here
),
'frontacc' => array(
//code here
)
[array][db][table][field]
As you can see, the database currently populated refers to an RSS project I am working on - one table for Channels, another for Items in that channel, at the moment that is another issue ('Users' table for now is not important)..
what I want to do is to return the array/sub-array names and convert each into variables for use as part of a string in an SQL Query, also need an alias for the tables I need to connect with:
(e.g. SELECT * FROM 'webref_rss_items' WHERE 'chan_id' = 'test.webref_rss_details.id')
where 'webref_rss_items' is a variable, 'chan_id' is a variable and 'test.webref_rss_details.id' are 3 variables in a concatenated string, although I've heard the concatenation in an SQL Query is not good practice, security-wise.. the strange thing is of all of those values, all I can retreive is the deepest level, 'id':
echo "{$da_db['test']['webref_rss_details'][0]}"
but get 'Array' returned or the last value of an array when I try to access the names!!
The reason for this is that the PHP file with the query will be within the 'public' part of the server and would like to have use variables with have no connotation to the original name(s), also it seems more convenient as the variables can be interchangable and I won't be using the same path all the time.
EDIT: My idea is to get key names from ['db'] to ['field']. The closest I have reached is to iterate keys and array_fill in a foreach loop, use range() inside another foreach, array_combine both then var_dump combined array like so:
foreach($da_db['test'] as $key1 => $val) { //put key-names into array1 to use as values
$a = array();
$a = array_fill(0, 1, $key1);
print($key1.'<br />');
}
foreach (range(0, 2) as $number) { //array for numbers to use as keys
$b = array();
$b = array_fill(0, 1, $number);
echo $number.'<br />';
}
$c = array_combine($b, $a); //combine both for new array
print_r($c.'<br />');
I could the use array_slice to get the name I want! (long winded?)
The problem is that the result of this only shows the last key => value; depending on command(print_r, print, echo), it shows:
[2] => webref_rss_items
OR
Array.
I hope that is enough info for now.
I've seen similar questions on here, but normally apply to one value, or one level of an array, but if you have seen this question before please advise and point me in right direction.
Your two top level arrays (db name and table name) are "named-key" arrays. The field level array (value of table name array) is an "integer key" array. PHP automatically adds numerical indexes for arrays that are defined with values only. For "named-key" arrays, you can only access their values by using the key name you defined.
For example:
$array1 = array('zero', 'one', 'two');
echo $array1[2]; // two
$array2 = array('zero' => 'this is zero', 'one' => 'this is one');
echo $array2['zero']; // this is zero
echo $array2[0]; // undefined
PHP provides a function called array_keys() that will return you an integer index array with all the key names. So you access your table array using an integer value, you can do this.
$da_db_test_keys = array_keys($da_db['test']);
echo $da_db_test_keys[1];
Maybe this will help you a little bit. I wasn't 100% on how you planned on accessing the values in your arrays, so if you have any more questions please try to clarify that part.