Select index based on another array in PHP - php

I have two arrays like this
Array
(
[0] => 1
[1] => 3
[2] => 4
[3] => 5
)
Array
(
[0] => Array
(
[1] => Test1
[2] => Location1
[3] => Email1
[4] => Name1
[5] => Address1
[6] => Age1
[7] => Gender1
[8] => Phone1
[9] => Website1
[10] => Cell1
)
[1] => Array
(
[1] => Test2
[2] => Location2
[3] => Email2
[4] => Name2
[5] => Address2
[6] => Age2
[7] => Gender2
[8] => Phone2
[9] => Website2
[10] => Cell2
)
[2] => Array
(
[1] => Test3
[2] => Location3
[3] => Email3
[4] => Name3
[5] => Address3
[6] => Age3
[7] => Gender3
[8] => Phone3
[9] => Website3
[10] => Cell3
)
)
Now i have to select 1,3,4 and 5 index value from each second array. How can i do this without two loops. I know i will have to use one but i don't want to use two loops
Output Required
Array
(
[0] => Array
(
[1] => Test1
[3] => Email1
[4] => Name1
[5] => Address1
)
[1] => Array
(
[1] => Test2
[3] => Email2
[4] => Name2
[5] => Address2
)
[2] => Array
(
[1] => Test3
[3] => Email3
[4] => Name3
[5] => Address3
)
)

Using one loop, array_flip, and array_intersect_key, you can do it like this:
$array_one = array(1, 3, 4, 5);
$array_two = array(
array(1 => 'Test1', 'Location1', 'Email1', 'Name1', 'Address1', 'Age1', 'Gender1', 'Phone1', 'Website1', 'Cell1'),
array(1 => 'Test2', 'Location2', 'Email2', 'Name2', 'Address2', 'Age2', 'Gender2', 'Phone2', 'Website2', 'Cell2'),
array(1 => 'Test3', 'Location3', 'Email3', 'Name3', 'Address3', 'Age3', 'Gender3', 'Phone3', 'Website3', 'Cell3')
);
$array_one_flip = array_flip($array_one);
foreach($array_two as $k => $v) {
$result[] = array_intersect_key($v, $array_one_flip);
}
print_r($result);
The result would be:
Array
(
[0] => Array
(
[1] => Test1
[3] => Email1
[4] => Name1
[5] => Address1
)
[1] => Array
(
[1] => Test2
[3] => Email2
[4] => Name2
[5] => Address2
)
[2] => Array
(
[1] => Test3
[3] => Email3
[4] => Name3
[5] => Address3
)
)

You could try it with array_intersect_key:
$keys = array_flip($keys_array); // flip the keys array for matching with array_intersect_key
$result = array();
foreach ($content_array as $arr)
{
$result[] = array_intersect_key($arr, $keys);
}
Working example on codepad. Thanks #Michael Irigoyen for the arrays...

Just use an array_map function like this:
$keys_to_keep = array(1, 3, 4, 5);
$key_diff_array = array_fill_keys($keys_to_keep, 'not used');
$array; // your main array you want to filter assume value has been set elsewhere
$filtered_array = array_map(function ($value) use $key_diff_array {
return array_intersect_key($value, $key_diff_array);
}, $array);

using one loop:
<?php
$selection = array(1, 3, 4, 5);
for($i = 0; $i < count($array); $i++){
reset($selection);
$first = current($selection);
$newarray[$i][$first] = $array[$i][$first];
$next = next($selection);
$newarray[$i][$next] = $array[$i][$next];
$next = next($selection);
$newarray[$i][$next] = $array[$i][$next];
$next = next($selection);
$newarray[$i][$next] = $array[$i][$next];
}
echo '<pre>';
print_r($newarray);

You might also find this Note about array_flip useful.
Ensure that $array1 has values that can be accepted as array keys when flipped.
http://php.net/manual/en/language.types.array.php
The key can either be an integer or a string. The value can be of any type.
Additionally the following key casts will occur:
Strings containing valid integers will be cast to the integer type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer.
Floats are also cast to integers, which means that the fractional part will be truncated. E.g. the key 8.7 will actually be stored under 8.
Bools are cast to integers, too, i.e. the key true will actually be stored under 1 and the key false under 0.
Null will be cast to the empty string, i.e. the key null will actually be stored under "".
Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.
If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.
http://www.php.net/manual/en/function.array-flip.php
array_flip() returns an array in flip order, i.e. keys from trans become values and values from trans become keys.
Note that the values of trans need to be valid keys, i.e. they need to be either integer or string. A warning will be emitted if a value has the wrong type, and the key/value pair in question will not be included in the result.
If a value has several occurrences, the latest key will be used as its value, and all others will be lost.

Related

How to sum 90+ Arrays with using function?

I would like to sum up several arrays. I have a script that dynamically creates arrays without name. Below is an example. In my script i have a 90+ arrays. I want to sum up all it. All keys in that arrays be user id, so i only want sum values of keys. How to do it? Regards
Array
(
[1] => 1
[2] => 1
[3] => 1
)
Array
(
[1] => 1
[2] => 1
)
Array
(
[1] => 1
)
I want to get only one array result like:
Array
(
[1] => 3
[2] => 2
[3] => 1
)
Add all your arrays into one array.
$all_arrays[] =Array
(
[1] => 1 ,
[2] => 1,
[3] => 1
);
$all_arrays[] = Array
(
[1] => 1,
[2] => 1
) ;
$all_arrays[] = Array
(
[1] => 1
);
$results = [];
foreach($all_arrays as $arr){
foreach($arr as $user_id=>$value){
if(in_array($user_id,$results)){
$results[$user_id] = $results[$user_id] + $value;
}else{
$results[$user_id] = $value;
}
}
}
You would need to specify all arrays in the array_merge:
$result = array_count_values(array_keys(array_merge($array1, $array2, $array3)));
If you can get the arrays dynamically added to another $main_array like:
Array
(
[0] => Array
(
[1] => 1
[2] => 1
[3] => 1
)
[1] => Array
(
[1] => 1
[2] => 1
)
[2] => Array
(
[1] => 1
)
)
Then it would be much easier:
$result = array_count_values(array_keys(array_merge(...$main_array)));

Removing null or blank values of array

I have an array, I just print it as-
print_r($data);
It shows output as-
Array
(
[0] => Array
(
[0] => Title
[1] => Featured Image
[2] => Catagories
[3] => Tags
[4] => Content
)
[1] => Array
(
[0] => title 1
[1] => img1.jpg
[2] => cat 1
[3] => tag 1
[4] => post 1 content
)
[2] => Array
(
[0] => title 2
[1] => img2.jpg
[2] => cat2
[3] => tag 2
[4] => post 2 content
)
[3] => Array
(
[0] => title 3
[1] => img3.jpg
[2] => cat3
[3] => tag3
[4] => post 3 content
)
[4] => Array
(
[0] =>
[1] =>
[2] =>
[3] =>
[4] =>
)
[5] => Array
(
[0] =>
[1] =>
[2] =>
[3] =>
[4] =>
)
[6] => Array
(
[0] =>
[1] =>
[2] =>
[3] =>
[4] =>
)
)
I just want to remove blank or null values from array.
I tried array_dif() and array_filter() but still I couldn't remove null values.
How is this possible?
Thanks.
You can loop through the array, look for empty variables and use unset to remove them.
This code will loop through and check if the length of the first value in each array is at least one character long and unset it if its not.
<?php
foreach($data as $key => $value) {
if(!isset($value[0][0]))
unset($data[$key]);
}
This code will loop through the array in a similar way, except to check every value of every array to determine if its parrent array should be kept or left to be unset.
<?php
foreach($data as $key => $values) {
foreach($values as $value) {
if(isset($value[0]))
continue 2;
}
unset($data[$key]);
}
You should use array_filter with a function that also runs array_filters against the subarrays and returns false if the filtered subarrays become empty.
<?php
$array = Array(
Array(1, 2, 3),
Array(null, null, null),
Array(false, false, false),
Array(3, 2, 1)
);
$filtered = array_filter($array, function($elem) {
return count(array_filter($elem));
});
print_r($filtered);
?>

Match array elements beginning with letters specified in another array in PHP

I have the following array:
Array
(
[0] => BCD
[1] => ACE
[2] => AHP
[3] => BGH
[4] => ART
[5] => COT
[6] => ARG
[7] => BGT
)
I need to match all elements whose first letter is in the following array:
Array
(
[0] => B
[1] => A
)
to get:
Array
(
[0] => ACE
[1] => AHP
[2] => BGH
[3] => ART
[4] => ARG
[5] => BGT
)
Short of looping through the whole array, how do I do this in PHP? Is there a built-in PHP array function for this or a combination of so? The order does not matter for both keys and values of the resulting array. Thanks much.
You can use array_filter for these operations:
$array = array('CBD', 'NHN', 'NHP', 'WHC', 'NND', 'CQN', 'WST', 'WVT');
$whitelist = array('W', 'N');
$filtered = array_filter($array, function($val) use ($whitelist) {
// check if first letter is in the whitelist array
if (in_array($val{0}, $whitelist)) {
return $val;
}
return false;
});
Output:
Array
(
[1] => NHN
[2] => NHP
[3] => WHC
[4] => NND
[6] => WST
[7] => WVT
)

How to combine both array and insert into database php

if only one array is there for example
$values = array(x, y, z);
i am adding them into database like this
foreach ($values as $value)
{
$insertFunction = addValues($value);
}
my arrays:
$array1 = Array ( 1, 2, 1, 2, 1, 2, 1, 2, 1, 2 );
$array2 = Array ( fb1, or1, fb2, or2, fb3, or3, fb4, or4, fb5, or5 );
But i want both array to combine and insert them into database.
How can i do this please help me
Updated:
When i am printing the POST values i am getting out put like this
Array ( [0] => 1 [1] => 2 [2] => 1 [3] => 2 [4] => 1 [5] => 2 [6] => 1 [7] => 2 [8] => 1 [9] => 2 )
Array ( [0] => fb1 [1] => or1 [2] => fb2 [3] => or2 [4] => fb3 [5] => or3 [6] => fb4 [7] => or4 [8] => fb5 [9] => or5 )
when i tried with array_merge my out put is like this
Array ( [0] => 1 [1] => 2 [2] => 1 [3] => 2 [4] => 1 [5] => 2 [6] => 1 [7] => 2 [8] => 1 [9] => 2 [10] => fb1 [11] => or1 [12] => fb2 [13] => or2 [14] => fb3 [15] => or3 [16] => fb4 [17] => or4 [18] => fb5 [19] => or5 )
How to insert them in separate columns in a table $array1 and $array2
my database table is like this
1.id
2.username
3.network_id
id is primary key
network_id values coming in array1
username values coming in array2
EDIT:
After you mentioned seperated columns I think I understand what you're looking for:
I'm assuming that array1 and array2 are in the same size.
for($i = 0; $i < count($array1); $i++)
{
$array2[$i] = (int)$array2[$i]; //"validating" the username (an integer)
mysql_query("INSERT INTO yourTableName (`username`,`network_id`) VALUES('".$array2[$i]."','".$array1[$i]."')");
}
Result:
tblName:
username: 1 2 1 ...
network_id: fb1 or1 fb2 ...
Is that what you were looking for?
Ignore this and merging:
$combined = array_merge($array1 , $array2);
//$combined = Array ( 1, 2, 1, 2, 1, 2, 1, 2, 1, 2,fb1, or1, fb2, or2, fb3, or3, fb4, or4, fb5, or5 );
I think you need array_merge.
You can use array_merge(), function to merge multiple array into one.
$arrays = array_merge($array1 , $array2);
foreach ($arrays as $value)
{
$insertFunction = addValues($value);
}
If you want associate an element from array a to an element from array b, you have to use array_combine() function.
$arrays = array_combine($array1,$array2);
foreach ($array as $aValue)
{
$insertFunction = addValues($aValue);
}

Array sorting question

So I have an array such as this one:
Array
(
[-1] => Array
(
[3] => 3
[1] => 1
[6] => 6
[7] => 7
[5] => 5
)
)
It also contains some other keys that should not be modified.
I'd like to the numbers which are in a second array to come first (in the order of that second array), and then will be the numbers that don't exist in the second array, if any.
So for that matter, the second array would be:
Array
(
[0] => 6
[1] => 5
[2] => 3
)
And the final array should be as follows (please remember, there are some more keys inside of that array that should stay as they are):
Array
(
[-1] => Array
(
[6] => 6
[5] => 5
[3] => 3
[1] => 1
[7] => 7
)
)
Any ideas how that can be done?
Thanks!
It's not and shouldn't be termed as sorting but may be this code snippet may help you do what you want to:
$a1 = Array ( [-1] => Array ( [3] => 3 [1] => 1 [6] => 6 [7] => 7 [5] => 5 ) );
$a2 = Array ( [0] => 6 [1] => 5 [2] => 3 );
$sorted = getSortedArray($a1[-1] , $array2);
function getSortedArray($array1 , $array2){
$temp = Array();
$count = 0;
$totalKeys = sizeof($array2);
for($i=0;$i<sizeof($array2);$i++){
$temp[i] = $array1[$array2[i]];
unset($array1[$array2[i]]);
}
while($count!=sizeof($array1))
$temp[$totalKeys++] = $array1[$count++];
return $temp;
}
I believe the function you're looking for is called array_multisort().
array_multisort() can be used to sort
several arrays at once, or a
multi-dimensional array by one or more
dimensions.

Categories