PHP 2 arrays using one to chose from the other - php

I am new to php and my problem is i have 2 arrays the first one is from another page via post and read into an array via post_get
Array (
[0] => 93
[1] => 25
[2] => 5
[3] => 4
[4] => 36
)
and my second array looks like this
Array (
[25] => Estonia
[20] => France
[4] => Germany
[5] => Greece
[75] => Hungary
[93] => India
[36] => Italy
)
what i want to do is if the array looks like the first one then it uses the numbers from the array and with the help from the second array makes a new array that only contains
Array (
[0] => India
[1] => Estonia
[2] => Greece
[3] => Germany
[4] => Italy
)
and using this doesn't work
$group is the first array
$array is the one with the country names
foreach ($group as $value) {
if (in_array($value, $array)) {
}
else {
echo "The group ".$value." does not exist";
}
}

You can do this many ways. Here is a simple one:
$new = [];
foreach ($group as $groupId) {
if (isset($array[$groupId])) {
$new[] = $array[$groupId];
}
}

I would do it like this. Flip $group and find the key intersection with $array:
$result = array_intersect_key($array, array_flip($group));
That will retain the keys, so if you want to re-index:
$result = array_values(array_intersect_key($array2, array_flip($array1)));

No need to use in_array just add some if checking and two foreach loops and use the key of the first array to the index of the second one.
Idea:
$array3 = array();
foreach($array1 as $key) {
if(isset($array2[$key])) { // add some checking just so make sure no undefined indices
$array3[] = $array2[$key];
}
}

Another alternative solution using array_map function:
$result = array_map(function($v) use($array){
return isset($array[$v])? $array[$v] : $v;
}, $group);

Related

How to unset numeric index elements from a PHP array?

I have a collection of array it contains both numeric index as well as non numeric. I want to unset all the numeric indexes.
My array is something like this .
Array
(
[554] => Array
(
[0] => 554
[1] => Jiaqi Zheng
[2] => Female
[3] => 28
[4] => Table Tennis
[5] =>
[6] =>
[7] =>
[8] =>
[rank] => 554
[athlet_name] => Jiaqi Zheng
[gender] => Female
[sport] => Table Tennis
)
[555] => Array
(
[0] => 555
[1] => Zach Ziemek
[2] => Male
[3] => 23
[4] => Athletics
[5] =>
[6] =>
[7] =>
[8] =>
[rank] => 555
[athlet_name] => Zach Ziemek
[gender] => Male
[sport] => Athletics
)
)
Here i have to unset all the numeric index .
I used unset like this and its working fine for me .
unset(
$history_years_wise_country_wise_details_arr[ $history_years_wise_country_wise_details_info[0]][0],
$history_years_wise_country_wise_details_arr[$history_years_wise_country_wise_details_info[0]][1],
$history_years_wise_country_wise_details_arr[$history_years_wise_country_wise_details_info[0]][2],
$history_years_wise_country_wise_details_arr[$history_years_wise_country_wise_details_info[0]][3],
$history_years_wise_country_wise_details_arr[$history_years_wise_country_wise_details_info[0]][4],
$history_years_wise_country_wise_details_arr[$history_years_wise_country_wise_details_info[0]][5],
$history_years_wise_country_wise_details_arr[$history_years_wise_country_wise_details_info[0]][6],
$history_years_wise_country_wise_details_arr[$history_years_wise_country_wise_details_info[0]][7],
$history_years_wise_country_wise_details_arr[$history_years_wise_country_wise_details_info[0]][8]
);
Is there any way I will reduce the lines of codes? here 0 to 8 are in one series.
Can I unset all index in one line of code , as all are numeric?
Is it possible to use regular expression instead?
I want something like
unset(
$history_years_wise_country_wise_details_arr[ $history_years_wise_country_wise_details_info[0]][anything_which_will_take_index_from_0_to_8]);
Any suggestions?
Thank you
You could use array_filter() with is_string() function as its callback function:
$array = array_filter($array, 'is_string', ARRAY_FILTER_USE_KEY);
Use looping.
foreach ($array as $key => $value) {
if (is_numeric ($key)) {
unset($array [$key]);
}
}
Or use array_filter
$filtered = array_filter(
$array,
function ($key) {
return !is_numeric($key);
},
ARRAY_FILTER_USE_KEY
);
You shoud used foreach loop with is_numeric function like
foreach ($your_array as $key => $value) {
if (!is_numeric($key)) {
unset($arr[$key]);
}
}
i think there is no need of any regular expression
Since you have array inside array first you need to use array_map() and then traverse through array using array_filter(),
considering $array as your array:
$resultData = array_map([$this, 'allData'], $array);
public function allData($data)
{
$numericKeys = array_filter(array_keys($data), function ($k) {
return is_int($k);
});
// Updated Code
$arrayKeys = array_diff(array_keys($data),$numericKeys);
return array_intersect_key($data,array_flip($arrayKeys));
}

php array index entries auto populate

I have two arrays
$arrayOne = ( [0] => 4892 [1] => 98508 [2] => 7834 [3] => 47826 )
$arrayTwo = ( [1] => Car [2] => Computer )
Notice the elements of arrayTwo does not start at 0, but which is what i want because it will be used to pair with arrayOne, ie. Car matches with 98508.
I want to populate the second array where there are no entries with a string for example arrayTwo output:
$arrayTwo = ([0] => its empty [1] => Car [2] => Computer [3] => its empty
How can i achieve this desired output?
Loop the first and check for the key. If it doesn't exist, set it:
foreach($arrayOne as $key => $val) {
if(!isset($arrayTwo[$key])) { $arrayTwo[$key] = 'its empty'; }
}
foreach ($arrayOne as $key => $value){
if (!array_key_exists($key, $arrayTwo)){
$arrayTwo[$key] = 'its empty';
}
}

Change value depends on the position of an array in PHP

It seems I have a problem regarding arrays that would change the value of first array depending on the value and position of the second array. It would seem to hard to explain in words, I'll give an example to make this a little bit more of understanding.
I have this first array
Array
(
[0] => one
[1] => two
[2] => three
[3] => four
[4] => five
)
and this is my second array
Array
(
[0] =>
[1] => cat
[2] =>
[3] => dog
[4] =>
)
and my desired result should be like this
Array
(
[0] => one
[1] => cat
[2] => three
[3] => dog
[4] => five
)
so if I changed my second array into this
Array
(
[0] =>
[1] =>
[2] =>
[3] => dog
[4] => cat
)
The result would be like this
Array
(
[0] => one
[1] => two
[2] => three
[3] => dog
[4] => cat
)
So meaning, the second array would be like the replacement of the first array.
Well I used array_diff to get the difference of the two arrays and that's where I'm stuck.
Any help would be appreciated though.
There may be a better way but you could do something like:
for ($i = 0; $i < count($array1); $i++) {
if ($array2[$i] == null || $array2[$i] == "") {
$newArray[$i] = $array1[$i];
}
else {
$newArray[$i] = $array2[$i];
}
}
$newArray will contain all values from $array1 unless a non-null or empty value exists in $array2 (based on the array index), in which case it will overwrite the value that was in $array1.
Maybe this link about
array_merge
could be usefull
http://php.net/manual/en/function.array-merge.php
I think this should work:
foreach($second_array as $k => $v)
{
if($v != "")
{
$first_array[$k] = $v;
}
}
demo here
the easiest thing to do would be to loop through your second array and assign it's value to the first based on the key...
$arr1=array ("one","two","three","four","five");
$arr2=array( 2=>"cat",4="dog");
foreach ($arr2 as $key=>$value){
if (!empty($value)){
$arr1[$key]=$value;
}
}

Convert complex numerical array to associative array

I have an array data that look like this :
Array (
[0] => Array (
[0] => Name:
[1] => John W.
[2] => Registration ID:
[3] => 36
)
[1] => Array (
[0] =>Age:
[1] => 35
[2] => Height:
[3] => 5'11"
)
[3] => Array (
[0] => Sex:
[1] => M
[2] => Weight:
[3] => 200lbs
)
[4] => Array (
[0] => Address
)
[5] => Array (
[0] => 6824 crestwood dr delphi, IN 46923
))
And I want to convert it to associative array like this :
Array(
['Name']=> John W.
['Registration ID']=> 36
['Age']=> 35
['Height'] => 5'11''
['Sex']=>M
['Weight']=>200lbs
['Address']=>6824 crestwood dr delphi, IN 46923
)
I have no idea at all how to do this, since the supposed to be array column header were also in sequence, so it makes difficult to convert this array.
Any help I appreciate, thx.
Given your origin array is called $origin , you can do it like this:
$merged = array();
foreach($origin as $val) {
$merged = array_merge($merged, $val);
}
$tot = count($merged) - 1;
for ($i=0;$i<$tot;$i+=2) {
$result[$merged[$i]] = $merged[$i+1];
}
var_dump($result); // To test the resulting array
Firstly, I use array_merge() to flatten the $origin array to only one dimension/depth, so we later iterate it (stepping each 2 items per iteration) and assigning each pair of items ($i and $i+1) to the resulting array.
Looks like, for the first 3 children, you can just assign the even value to the previous element as key. Then, assign the fourth one as key for fifth element.
$result = array();
foreach ($array as $key => $value)
{
if ($key < 4) {
$elements = array_values($value);
$result[$elements[0]] = $elements[1];
$result[$elements[2]] = $elements[3];
}
if ($key == 4)
$fifthkey = $value;
if ($key == 5)
$result[$fifthkey] = $value;
}
Also, note that you have to escape your height string quotes.

combining arrays in php

Lets say I want to combine 2 arrays and the arrays are names $year_into and $likes_dislikes. They share a key called "name". How can I make it so that this one:
$year_info
Array
(
[0] => Array
(
[name] => JOE MONROE
[year] => 1950
[info] => his ghost still haunts us
)
[1] => Array
(
[name] => FUTUREMAN
[year] => 1930
[info] => RIP
)
)
and this one $likes_dislikes
Array
(
[0] => Array
(
[name] => JOE MONROE
[likes] => cornbread
[dislikes] => pain
)
[1] => Array
(
[name] => E. Case
[likes] => chaos
[dislikes] => order
)
[2] => Array
(
[name] => FUTUREMAN
[likes] => mustard
[dislikes] => mayo
)
)
Can be combined into one array $complete that looks like this, where the information from the 2nd array is added to the 1st if the "name" value matches:
Array
(
[0] => Array
(
[name] => JOE MONROE
[year] => 1950
[info] => his ghost still haunts us
[likes] => cornbread
[dislikes] => pain
)
[1] => Array
(
[name] => FUTUREMAN
[year] => 1930
[info] => RIP
[likes] => mustard
[dislikes] => mayo
)
)
I've looked through the already asked questions but don't see anything, maybe I'm using the wrong terminology to describe the problem. I'm stuck on the foreach loop because if I say like this
foreach ($year_info as $y){
$complete[]=array('name'=>$y['name'], 'year'=>$y['year'], 'info'=>$y['info'], 'likes'=$likes_dislikes[0]['likes'],'dislikes'=>$likes_dislikes[0]['dislikes'] )
}
I'll just get the same values for likes/dislikes for all. What is the simplest way to do this?
Here's a crazy one-liner (I guess it technically counts as one line), that should work.
$complete = array_map(function($a) use($likes_dislikes){
foreach($likes_dislikes as $ld){
if($a['name'] === $ld['name']){
return $a + $ld;
break;
}
}
}, $year_info);
This will only work in PHP 5.3+, otherwise you can do it like this:
$complete = array();
foreach($year_info as $a){
foreach($likes_dislikes as $ld){
if($a['name'] === $ld['name']){
$complete[] = $a + $ld;
break;
}
}
}
What I would try to do is loop through both sets of arrays (a nested foreach loop would be a good choice), checking for instances where The name attribute is the same in both arrays. When they are, you can use array_merge() to merge them into a new array. An example would be:
$newArray = array();
foreach ($arr1 as $first) {
foreach ($arr2 as $second) {
if($first["name"] == $second["name"]){
array_push($newArray, array_merge($first, $second));
}
}
}
Assuming you named your arrays $arr1 and $arr2.
The super-lazy, extra-expository approach:
$complete = array();
foreach($year_info as $yr){
$name = $yr['name'];
foreach($likes_dislikes as $ld){
if($ld['name']!=$name){
continue;
}else{
$new_entity = array();
$new_entity['name'] = $name;
$new_entity['year'] = $yr['year'];
$new_entity['info'] = $yr['info'];
$new_entity['likes'] = $ld['likes'];
$new_entity['dislikes'] = $ld['dislikes'];
$complete[] = $new_entity;
break;
}
}
}
Though this will perform poorly with large arrays, it would make more sense to change the data structure if possible. It would be better to have data structures that were simply keyed by name. Do you have control over your input?
just loop over both arrays to create a third one.
$complete = array();
foreach ($year_info as $year) {
foreach ($like_dislikes as $like {
if ($year['name'] == $like['name']) {
$complete[] = array_merge($year, $like);
}
}
}

Categories