Change value depends on the position of an array in PHP - 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;
}
}

Related

How to combine 2 arrays of different lengths while dropping part of one array?

I have 2 arrays
array 1: Array ( [0] => Merc [1] => # [2] => BM [3] => & [4] => Lotus )
array 2: Array ( [0] => 6740 [1] => 4565 [2] => 3423 )
The goal is to combine the 2 arrays and end up with:
$result = ['Merc' => 6740, 'BM' => 4565, 'Lotus' => 3423];
There is a fair amount of guidance on this already, I know, and I have read up on it but array manipulation is new to me and somehow I just cannot get my head around the logic and syntax.
Please could someone with an experienced eye tell me where I am going wrong.
I have tried:
...
//// lets echo the arrays to make sure they are correct
print_r($car);?><br><?php
print_r($part);?><br><?php
//// lets combine the 2 arrays to get an associative array
$result = [];
for($i = 0; $i < count($car); $i++){
if (($car[$i] == "&")||($car[$i] == "#")){
$i = ($i + 1);
}
foreach($car as $car) {
foreach($part as $part) {
$result[] = array(
$car => $part,
);
}
}
}
print_r($result);
The output for this is:
Array ( [0] => Array ( [Merc] => 6740 ) [1] => Array ( [BM] => 4565 ) [2] => Array ( [Lotus] => 3423 ))
The special characters to be stripped will only ever be # or &
Filter out the unwanted elements and combine them.
Code: (Demo)
$cars=['Merc','#','BM','&','Lotus'];
$parts=[6740,4565,3423];
$cars=array_diff($cars,['#','&']);
var_export(array_combine($cars,$parts));
Output:
array (
'Merc' => 6740,
'BM' => 4565,
'Lotus' => 3423,
)
p.s. You could also filter with ctype_alpha() like this: (Demo)
$cars=array_filter($cars,'ctype_alpha'); // only retain elements that are fully comprised of letters

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';
}
}

creating one array out of multiple arrays and concatenating unique values in a certain key

I need to loop through a bunch of arrays that I am getting back from mysql that contain a lot of duplicate entries and create one array out of several. The arrays will have one or more unique values in them so I need to keep these but some how concatenate them together into one string using commas or semicolons. So far I am not having any luck with this. Here is a phpfiddle
I need it to create a single array like this:
Array
(
[0] => Array
(
[0] => test
[1] => test
[2] => test
[3] => one
[4] => two
)
[1] => Array
(
[0] => test1
[1] => test
[2] => test
[3] => three
[4] => four
)
[2] => Array
(
[0] => test2
[1] => test
[2] => test
[3] => five, seven
[4] => six, eight
)
[3] => Array
(
[0] => test3
[1] => test
[2] => test
[3] => nine
[4] => ten
)
)
from an array like this
Array
(
[0] => Array
(
[0] => test
[1] => test
[2] => test
[3] => one
[4] => two
)
[1] => Array
(
[0] => test1
[1] => test
[2] => test
[3] => three
[4] => four
)
[2] => Array
(
[0] => test2
[1] => test
[2] => test
[3] => five
[4] => six
)
[3] => Array
(
[0] => test2
[1] => test
[2] => test
[3] => seven
[4] => eight
)
[4] => Array
(
[0] => test3
[1] => test
[2] => test
[3] => nine
[4] => ten
)
)
this is what I am trying:
for($i=0; $i < count($arrayBIG); $i++) {
if($arrayBIG[$i][0] == $arrayBIG[$i+1][0]) {
$clean[$i] = array(array_unique(array_merge($arrayBIG[$i],$arrayBIG[$i+1]), SORT_REGULAR));
}
}
Okay, so I made a new answer based on your updated post. This one was quite a bit more work than the previous version, but here's the rundown: First, I looped through the big array and for each first element, I checked to see if it also appeared in the array multiple times. If it did, I noted down each location in the array so I know which elements to "merge" and then update later.
After some looping, we can locate the "columns" of data from all of the similar arrays and merge them together by using array_unique and then imploding them into a string.
Finally, reconstruct the array, unset the original items and insert our new & improved array to the original location.
// DEFAULT ARRAY
$arrayBIG = array(
array('test', 'test', 'test', 'one', 'two'),
array('test1', 'test', 'test', 'three', 'four'),
array('test1', 'test', 'test', 'asdfasd', '443llpapos'),
array('test1', 'test', 'test', '94niwnoowi', 'inoinwoinw'),
array('test2', 'test', 'test', 'five', 'six'),
array('test2', 'test', 'test', 'seven', 'eight'),
array('test3', 'test', 'test', 'nine', 'ten')
);
// STORE THE ITEM OF EACH ARRAY INTO AN ARRAY OF ITS OWN SO WE CAN CHECK FOR DUPES
foreach ($arrayBIG AS $item_array) {
$temp_array[] = $item_array[0];
}
// COUNT THE VALUES OF THE ARRAY AND STORE ANY KEYS THAT APPEAR MORE THAN ONCE
// THESE WILL BE THE ITEMS WE TRY AND MERGE
// THIS WILL NOT BE THE NUMERIC KEY, BUT THE TEXT OF THE KEY - EX: 'test2'
foreach(array_count_values($temp_array) AS $item_count_key => $item_count_val) {
if ($item_count_val > 1) {
$dupe_key_array[] = $item_count_key;
}
}
// LOOP THROUGH THE DUPE KEYS AND FIND THEIR POSITIONS, THEN MERGE THE SIMILAR ITEMS
foreach ($dupe_key_array AS $dupe_key) {
$dupe_keys = array();
$new_array = array();
// FOR EACH MAIN ARRAY, NOTE THE ACTUAL NUMERIC LOCATION OF THE VALUE IN THE MAIN ARRAY
foreach ($arrayBIG AS $array_big_key => $array_big_val) {
// WHEN WE FIND A MATCH, ADD THE NUMERIC VALUE TO THE ARRAY
// THESE WILL BE THE ITEMS THAT WILL BE REPLACED IN THE FINAL ARRAY
if ($array_big_val[0] == $dupe_key) {
$dupe_keys[] = $array_big_key;
}
}
// FOR EACH ITEM, PULL OUT THE "COLUMN" AND MERGE THEM
for($i = 0; $i < count($array_big_val); $i++) {
$temp_array_1 = array();
// FOR EACH DUPE, GET EACH INDIVIDUAL ITEM FROM EVERY POSITION AND PUT THEM INTO A TEMP ARRAY
// THIS WILL BE THE "COLUMN" FOR EACH ARRAY.
foreach ($dupe_keys AS $dupe_keys_val) {
$temp_array_1[] = $arrayBIG[$dupe_keys_val][$i];
}
// FILTER OUT DUPES AND THEN IMPLODE IT INTO A COMMA-SEPARATED STRING
$new_array[] = implode(', ', array_unique($temp_array_1));
}
// UNSET ALL OF THE ITEMS THAT WE ARE GOING TO BE REPLACING
foreach ($dupe_keys AS $array_item_to_remove) {
unset ($arrayBIG[$array_item_to_remove]);
}
// FIND THE FIRST ITEM IN THE ARRAY WE ARE GOING TO REPLACE
// WE WILL INSERT THE NEW ARRAY AT THIS LOCATION
$first_array_item_to_replace = array_shift($dupe_keys);
// SPLICE THE MAIN ARRAY AND ADD IN OUR NEW MERGED ARRAY AT THE FIRST POSITION
array_splice($arrayBIG, $first_array_item_to_replace, 0, array($first_array_item_to_replace => $new_array));
}
I looped through your initial code and was able to just reassign the variables into a temporary array. I pulled out the same item from each element of $arrayBIG:
$arrayBIG[0][1]
$arrayBIG[1][1]
$arrayBIG[2][1] ...
Then, I did an array unique on those arrays and imploded them into a string. Finally, I added that string to the final output array. It looks like you've changed the question's code on the post since I wrote this, but the concepts should still be the same.
$arrayBIG = array( 0 => array("test", "test", "test", "one", "two"),
1 => array("test", "test", "test", "three", "four"),
2 => array("test", "test", "test", "five", "six"));
$new_array = array();
for ($j = 0; $j < count($arrayBIG[0]); $j++) {
$temp_array = array();
for ($i = 0; $i < count($arrayBIG); $i++) {
$temp_array[] = $arrayBIG[$i][$j];
}
$new_array[] = implode(', ', array_unique($temp_array));
}
That code will have $new_array outputting this:
Array
(
[0] => test
[1] => test
[2] => test
[3] => one, three, five
[4] => two, four, six
)

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