I have an array like:
Array (
[0] => Array (
[A] => khaja.ghc#cdc.com
)
[1] => Array (
[A] => bag#example.com
)
)
Is there any easy process to store khaja.ghc#cdc.com and bag#example.com in an array in php? If so please help me.
I am doing this by foreach() method and after getting element I stored them in an array. Then finally by array_push() method I got the required array. But I think I missed easy process. Can you help me .
You still can use foreach modifing the value. Try
foreach($array as $key => &$value) {
if(is_array($value) && isset($value['A'])) $value = $value['A'];
}
and your $array will look like you want it to look.
If I understand well your question:
$data = array(array('A' => 'khaja.ghc#cdc.com'), array('A' => 'bag#example.com'));
$result = array();
foreach($data as $element)
if (is_array($element) && isset($element['A']))
$result[] = $element['A'];
print_r($result);
If you want to save a couple lines of code you can use array_map and create_function:
$a = array(array('A' => 'khaja.ghc#cdc.com'), array('A' => 'bag#example.com'));
$result = array_map(create_function('$x','$y = array_values($x); return $y[0];'), $a))
Although the saving on the number of code lines, I don't encourage you to take this approach. The code will be much easier to read and understand with a simple foreach loop.
Related
I have a post array and need to create a new array format from this to store in database with batch insert. I have achieved it with the following code. But want a better solution (if any) to achieve my array. I wanted to eliminate the inner loop but did not get any solution. Please provide any suggestion on how can I achieve this.
Code to parse array:
if ($this->input->post()) {
foreach ($this->input->post() as $key => $value) {
$i = 0;
/* need to eliminate this loop */
foreach ($value as $k => $v) {
$postData[$i][$key] = $v;
$i++;
}
}
}
Input array:
Array
(
[category_id] => Array
(
[0] => 1
[1] => 4
)
[pay_type_id] => Array
(
[0] => 2
[1] => 5
)
[frequency_id] => Array
(
[0] => 3
[1] => 6
)
)
Output array;
Array
(
[0] => Array
(
[category_id] => 1
[pay_type_id] => 2
[frequency_id] => 3
)
[1] => Array
(
[category_id] => 4
[pay_type_id] => 5
[frequency_id] => 6
)
)
If you really want to, you can do this without loops at all:
$input = $this->input->post();
$keys = array_keys($input);
$postData = [
array_combine($keys, array_column($input, 0)),
array_combine($keys, array_column($input, 1)),
];
This will give the same $postData output as your example, assuming that the input only has keys 0 and 1 in the inner arrays, as it does in your example. If the number of possible elements in the inner arrays is unknown, then you may need to introduce a loop on that, but the secondary loop can still be avoided.
I had to use array_combine() as well as array_column() as array_column() on it's own does not preserve the named keys the your top level of your array.
Other solutions using array_map() or array_walk() may also exist.
However, while it's short and concise, it isn't exactly clear for a reader to understand what it's doing, so unless you document it clearly, you'll be creating a maintenance headache for yourself in the long term.
The double-loop is a more readily understandable solution, pretty standard, and won't cause you any issues. So while I've given you a solution, I would actually recommend just using the code you've got.
Because you have two arrays, a:"records" and b:"fields" in any case, theoretically, you need to have at least two loops to populate the "records" and "fields" inside a record. And, basically, this is not a bad approach or a problem.
If you really want just one loop, because of faith reasons, you need to put a hard-coded list of field assignments in first loop that populate the records.
The only way I can see to do it without a second array is like this:
$arr = array("category_id" => array(1, 4), "pay_type_id" => array(2, 5), "frequency_id" => array(3, 6));
foreach ($arr as $key => $value) {
$postData[0][$key] = $value[0];
$postData[1][$key] = $value[1];
}
print_r($postData);
But you lose flexibility with this approach, because you have to know in advance how many indexes there will be in the inner arrays. The only way to make it generic enough to cope with changes in data is to use an inner loop similar to how you did it originally.
There's nothing much wrong with your original code, it's a pretty standard and reasonable approach to changing the array format in this scenario. It shouldn't give you any particular performance issues, even with fairly large arrays, and there's not really any neater way to approach it.
As per your ouput you need second loop also. But yes you can eliminate use of $i you can use $k instead.
You can change your code as:
if ($this->input->post()) {
foreach ($this->input->post() as $key => $value) {
foreach ($value as $k => $v) {
$postData[$k][$key] = $v;
}
}
}
DEMO
Given:
$arr_in=array('a'=>1,'b'=>2,'c'=>3,'d'=>4);
$keep=array('a','c');
What is the most concise way to obtain:
$arr_out=array('a'=>1,'c'=>3); //Keep only original elements who's index is in $keep
You can achieve this as a one-liner with array_flip() and array_intersect_key():
$arr_out = array_intersect_key($arr_in, array_flip($keep));
print_r($arr_out);
Yields:
Array
(
[a] => 1
[c] => 3
)
Try using:
foreach($arr_in as $key => $val){
if(in_array($keep, $key))
$temp[$key] = $val;
}
You might want to look into array functions like array-pop.
I have an array $templates that looks like this:
Array
(
[0] => Array
(
[displayName] => First Template
[fileName] => path_to_first_template
)
[1] => Array
(
[displayName] => Second Template
[fileName] => path_to_second_template
)
[2] => Array
(
[displayName] => Third template
[fileName] => path_to_third_template
)
)
And I want to make it to look like this:
Array
(
[path_to_first_template] => First Template
[path_to_second_template] => Second Template
[path_to_third_template] => Third Template
)
That is, I want the fileName of the nested arrays to be the new array's key and displayName to be its value.
Is there a pretty way to do this without having to loop through the array. I had no luck searching, as I didn't know exactly what to search for.
Here's a classic foreach in action:
$result = array();
foreach($array as $row) {
$result[$row['fileName']] = $row['displayName'];
};
Here's a "clever" way to do it:
$result = array();
array_walk($array, function($row) use (&$result) {
$result[$row['fileName']] = $row['displayName'];
});
As you can see, the second approach is not really better than the first one. The only advantage is that theoretically you can pile upon the second form because it is a single expression, but in practice it's a long enough expression already so you wouldn't want to do that.
Loop in your array and make a new one:
$newArray = array();
foreach($array as $val){
$newArray[$val['fileName']] = $val['displayName'];
}
print_r($newArray);
$ret = array()
foreach ($templates as $template) {
$ret[$template["fileName"]] = $template["displayName"];
}
Total PHP Noob and I couldn't find an answer to this specific problem. Hope someone can help!
$myvar is an array that looks like this:
Array (
[aid] => Array (
[0] => 2
[1] => 1
)
[oid] => Array(
[0] => 2
[1] => 1
)
)
And I need to set a new variable (called $attributes) to something that looks like this:
$attributes = array(
$myvar['aid'][0] => $myvar['oid'][0],
$myvar['aid'][1] => $myvar['oid'][1],
etc...
);
And, of course, $myvar may contain many more items...
How do I iterate through $myvar and build the $attributes variable?
use array_combine()
This will give expected result.
http://php.net/manual/en/function.array-combine.php
Usage:
$attributes = array_combine($myArray['aid'], $myArray['oid']);
Will yield the results as requested.
Somthing like this if I understood the question correct
$attributes = array();
foreach ($myvar['aid'] as $k => $v) {
$attributes[$v] = $myvar['oid'][$k];
}
Your requirements are not clear. what you mean by "And, of course, $myvar may contain many more items..." there is two possibilties
1st. more then two array in main array. like 'aid', 'oid' and 'xid', 'yid'
2nd. or two main array with many items in sub arrays like "[0] => 2 [1] => 1 [2] => 3"
I think your are talking about 2nd option if so then use following code
$aAid = $myvar['aid'];
$aOid = $myvar['oid'];
foreach ($aAid as $key => $value) {
$attributes['aid'][$key] = $value;
$attributes['oid'][$key] = $myvar['oid'][$key];
}
You can itterate though an array with foreach and get the key and values you want like so
$attributes = array()
foreach($myvar as $key => $val) {
$attributes[$key][0] = $val;
}
I have two arrays that I would like to compare and ultimately wind up with a single array with everything combined, having no duplicates. Can someone please tell me which function I should use? There are so many that it's a bit confusing.
$array1[]['name'] = 'Kim, Jones';
$array1[]['name'] = 'Jim, Miller';
array1 is an array I built that I want added to an array coming from the database. The key in the second array is also named "name". Thanks.
EDIT:
I managed to merge these two arrays but I can still see duplicates.
This is what the first array looks like:
Array
(
[0] => Array
(
[WNumber] => ADMIN
[Name] => Tim, Cooley
[Employer] => CalPERS
[Student] => 1
[Perm] => 1
[QA] => 0
[Supervisor] => 1
[RQW] => 0
)
My second array is built like this:
$add_names[]['Name']='Jim, Jones';
I just want to add $add_names to the first array WHERE there are no duplicates.
I'm tempted to sell you on CakePHP, since it has a number of functions that makes this easy in its "Set" class. Your problem is that you have the results in a nested array. A simple "array_unique" does not work in a nested array.
I'd do it the old fashioned way...
$array1[]['name'] = 'Kim, Jones';
$array1[]['name'] = 'Jim, Miller';
$array2[]['name'] = 'Kim, Jones';
$array2[]['name'] = 'Jimbo, Miller';
$array2[]['name'] = 'Jim, Jones';
$new_array=array_merge($array1, $array2);
$out_array = array();
$key_array = array();
foreach($new_array as $i => $row) {
if (empty($key_array[$row['name']])) {
$out_array[] = $row;
}
$key_array[$row['name']] = 1;
}
print_r($out_array);
This code works for me...
I think you'll need to use a combination of array_merge (adds the two arrays together) and array_unique (removes duplicate values).
$resulting_array = array_unique(array_merge($array1, $array2));
Note that array_unique will not work correctly when using multi-dimensional arrays, so if your array data looks the way you put it in your question, you'll have to think of a way around that. One of the comments on the array_unique page suggests serialize'ing all array values before running array_unique on it. Afterwards you'd just run unserialize on all array elements. Note that this can mean a performance hit if you have a big array, so you might want to consider avoiding multi-dimensional arrays in this scenario.
Something like this:
$merged_array = array_merge($array1, $array2);
$serialized_array = array_map("serialize", $merged_array);
$filtered_array = array_unique($serialized_array);
$final_array = array_map("unserialize", $filtered_array);
There isn't a direct function for handling what you are looking for in php, probably you need to write a function for it.
What I understood from your question is that you have 2 arrays :
$a = array( array( 'name' => 'Omid' ), 12 );
$b = array( array( 'name' => 'testing' ) );
and you want to merge them to get
$merge = array( array( 'name' => 'testing' ), 12 );
if that's what you want then you might want to take a look at this comment array merge recursive which leads to this code :
function array_merge_recursive_distinct ( array &$array1, array &$array2 )
{
$merged = $array1;
foreach ( $array2 as $key => &$value )
{
if ( is_array ( $value ) && isset ( $merged [$key] ) && is_array ( $merged [$key] ) )
{
$merged [$key] = array_merge_recursive_distinct ( $merged [$key], $value );
}
else
{
$merged [$key] = $value;
}
}
return $merged;
}
Does php's array_diff() do what you want?
http://us.php.net/manual/en/function.array-diff.php
or more likely array_diff_assoc:
http://us.php.net/manual/en/function.array-diff-assoc.php
Does array_diff work for you?
Description
array array_diff ( array $array1 , array $array2 [, array $ ... ] )
Compares array1 against array2 and returns the difference.