Transfer keys from a 2D array to fill a 1D array - php

PHP has plenty of useful functions and Im wondering if Im overlooking one that has already been built.
Lets say you have an array such as:
$first_array = array("Name"=>"Angela", "Age"=>24);
and you wanted to grab the keys from the first array to create a second array (which could then be pushed into a third array). So you need to create:
$second_array = array("Name", "Age");
Is there a way to achieve this result without this loop?:
foreach($first_array as $k=>$v){
array_push($second_array, $k);
}

This should do it:
array_keys($first_array);

Use array_keys($first_array) to get the array of all the keys in the $first_array

Related

Execute same logic for multiple multidimensional arrays

I'm currently trying the following:
I have multiple arrays defined. They all are filled by fetching data from the database, so they all contain the same columns/data structure, but with different data. For example, lets say the arrays are different schools, so there is:
//pseudoCode:
array1 = ({"Name: Peter", "Surname: not peter"},{"Name: doe", "Surname: john"});
array2 = ({"Name: asfwe", "Surname: qwfqwf"},{"Name: asfas", "Surname: fsbng"});
array3 = ({"Name: weqw", "Surname: wqeqewqw"},{"Name: doqweqwee", "Surname: wewe"});
Now, for all these arrays, I want to do the same things. In my case, I have multiple if else cases, checking the length of the array and doing some stuff.
So far I'm only doing it for array 1 though. Now my first idea was to simply copy the logic and refactor all variable names to array2 respectively to array3, but this wouldn't make sense, because in my real case, its 10 arrays instead of 3 and the logic is about 150 lines of code, so I would have a lot of duplicate code and would need to change it everywhere, if something in the logic changes.
Now the question is: How can I do the same procedure for every array?
So what I would need is something like:
//pseudoCode again
foreach(array in array1, array2, array3, array4, array5,....){
//do something with variable "array", which is actually one of the defined arrays
}
A hint in the right direction would be great.
Thank you in advance.
Procedure code demand exporting logic to function:
function foo($array) {
// modify the array or do what ever you need
return $array; // in case it has been modify
}
Now can you function as:
foreach($arrays as &$arr)
$arr = foo($arr); // calling the function on each array
// the re-assign is just in case it has been modify
In this example $arrays stand for array with all your inner arrays as:
$arrays = array($array1, $array2, $array3, ...)
if your array as getting dynamicly from some other function / SQL code do:
$arrays = []; // init empty array
while (#SOME_CONDITION#) {
$arrays[] = getAnotherArrayFunction(); // append the array to your array
}

Store Get-Values from form in Array PHP

I'm trying to store the users's input via the method get in an array to store it and further process it without overwriting the initial get-value. But I dont know how.. do I have to store them in a database to do that? Or can I just push every input into an array?
I believe the following should work for you... This will take all the $_GETs that you supply and put them in a new array so you can modify them without affecting the original $_GET array.
if(is_array($_GET)){
$newArr = $_GET; // modify $newArr['postFieldName'] instead of $_GET['postFieldName'] to preserve original $_GET but have new array.
}
That solution there will dupe the $_GET array. $_GET is just an internal PHP array of data, as is $_POST. You could also loop through the GETs if you do not need ALL of the GETs in your new array... You would do this by setting up an accepted array of GETs so you only pull the ones you need (this should be done anyways, as randomly accepting GETs from a form can lead to some trouble if you are also using the GETs for database/sql functions or anything permission based).
if(is_array($_GET) && count($_GET) > 0){
$array = array();
$theseOnly = array("postName", "postName2");
foreach($_GET as $key => $value){
if(!isset($array[$key]) && in_array($key, $theseOnly)){ // only add to new array if they are in our $theseOnly array.
$array[$key] = $value;
}
}
print_r($array);
} else {
echo "No $_GET found.";
}
I would just add to what #Nerdi.org said.
Specifically the second part, instead of looping through the array you can use either array_intersect_key or array_diff_key
$theseOnly = array("postName", "postName2");
$get = array_intersect_key( $_GET, array_flip($theseOnly);
//Or
$get = array_diff_key( $_GET, array_flip($theseOnly);
array_intersect_key
array_intersect_key() returns an array containing all the entries of array1 which have keys that are present in all the arguments.
So this one returns only elements you put in $theseOnly
array_diff_key
Compares the keys from array1 against the keys from array2 and returns the difference. This function is like array_diff() except the comparison is done on the keys instead of the values.
So this one returns the opposite or only elements you don't put in $theseOnly
And
array_flip
array_flip() returns an array in flip order, i.e. keys from array become values and values from array become keys.
This just takes the array of names with no keys (it has numeric keys by default), and swaps the key and the value, so
$theseOnly = array_flip(array("postName", "postName2"));
//becomes
$theseOnly = array("postName"=>0, "postName2"=>1);
We need the keys this way so they match what's in the $_GET array. We could always write the array that way, but if your lazy like me then you can just flip it.
session_start();
if(!isset($_SESSION['TestArray'])) $_SESSION['TestArray'] = array();
if(is_array($_GET)){
$_SESSION['TestArray'][] = $_GET;
}
print_r($_SESSION['TestArray']);
Thanks everybody for helping! This worked for me!

Remove element from associative array in PHP

I need to remove a element from an associative array with an string structure.
Example:
$array = array(
"one"=>array("Hello", "world"),
"two"=>"Hi"
)
I want to create a function that removes the elements like this:
function removeElement($p) {
// With the information provided in $p something like this should happen
// unset($array["one"]["hello"])
}
removeElement("one.hello");
Your base array is associative, the inner array (key one) is not, its a indexed array, which you can not access via ["hello"] but rather [0].
You can remove the hello value by using the unset function, but the indexes will stay as they are:
$array = ['Hello', 'World']; // array(0: Hello, 1: World)
unset($array[0]); // Array is now array(1: World)
If you wish to keep unset and keep the array indexes in order, you can fetch the values using the array_values function after unset:
unset($array[0]);
$array = array_values($array); // array(0: World)
Or you could use array_splice.
When it comes to using a string as key for multidimensional array with a dot-separator I'd recommend taking a look at laravels Arr::forget method which does pretty much exactly what you are asking about.
This would be a static solution to your question, in any case, you need to use explode.
function removeElement($p, $array) {
$_p = explode('.', $p);
return unset($array[$_p[0]][$_p[1]]);
}
But bear in mind, this doesn't work if you have more in $p (like: foo.bar.quux)

PHP retrieve array of items from a multidimensional array without looping?

I have a large array of arrays and each of these sub-arrays has an ID and some other info. Is there a way to access an array of just the ID's without using a loop?
Sort of like
$array[ALLOFTHEITEMS][Id];
I want to eventually compare these ID's to another flat array of ID's.
I would usually do a for loop and then just add the id of each item to a new array and then compare them. But is there a faster way?
Not sure if its faster then foreach as I've never benchmarked it but an alternative to foreach would be:
php 5.3
$ids = array_map(function($data) { return $data['id']; }, $array);
php < 5.3
function reduceToIds($data) {
return $data['id'];
}
$ids = array_map('reduceToIds', $array);
I normally use the foreach approach myself though.

Adding arrays to multi-dimensional array within loop

I am attempting to generate a multi-dimensional array with each sub array representing a row I want to insert into my DB. The reason for this is so I can use CodeIgniters batch_insert function to add each row to the DB.
I am attempting to create each sub array within a loop and insert it into a multidimensional array. Google suggested using array_merge, but after using 'print_r' on the multidimensional array with the code below, only the last sub-array is being displayed.
Here is my code:
$allplayerdata = array(); //M-D container array
for ($i = 1; $i <= 11; $i++)
{
$playerdata = array(
'player_id' => $this->input->post('player' . $i),
'goals' => $this->input->post('playergoals' . $i),
'player_num' => $i,
'fixture_id' => $this->input->post('fixture_id')
);
//Merge each player row into same array to allow for batch insert
$allplayerdata = array_merge($allplayerdata, $playerdata);
}
print_r($allplayerdata);
Can anyone spot where I'm going wrong? Help is appreciated!
This is because array_merge is not the right operation for this situation. Since all the $playerdata arrays have the same keys, the values are overridden.
You want to use array_push to append to an array. This way you will get an array of $playerdata arrays.
array_push($allplayerdata, $playerdata);
Which is equivalent to adding an element with the square bracket syntax
$allplayerdata[] = $playerdata;
array_merge - Merge one or more arrays
array_push - Push one or more elements onto the end of array
Creating/modifying with square bracket syntax
This will add the second array to the first array: A merge is something different.
$allplayerdata[] = $playerdata;

Categories