Extract parts from Array keys in php and combine them - php

i have also got a similar question. I have an array where i need to extract parts from the keys of array and combine them. can you please suggest the best way for it.
$myarray=Array(
[0]=>'unwanted text'
[1]=>'unwanted+needed part1'
[2]=>'needed part2'
[3]=>'needed part3'
[4]=>'unwanted text'
)
how can i extract only the needed parts and combine them. Thanks a lot ahead.

Not exactly sure if this does what you want, but looping and copying to a new array should basically achieve your result (once you clarify how you decide which part of the strings are needed or unwanted)
$myarray = array(…);
$new_array = array();
$unwanted = 'some_string';
foreach($myarray as $k => $v) {
$new_value = preg_replace("/^$unwanted/", '', $v); # replace unwanted parts with empty string (removes them);
if(!empty($new_value)) { # did we just remove the entry completely? if so, don't append it to the new array
$new_array[] = $v; # or $new_array[$k] if you want to keep indices.
}
}
Assuming you want to join array entries and have a string as result, use the implode function of PHP: $string = implode(' ', $new_array);

The functions you are after, depending on what you want to do, will be a combination of the following: array_splice, array_flip, array_combine.
array_splice()
allows you to extract part of an array by key offset. It'll permanently remove the elements from the source, and return these elements in a new array
array_flip()
Turns keys into values and values into keys. If you have multiple identical values, the last one has precedence.
array_combine() takes two parameters: an array of keys, and an array of values, and returns an associative array.
You'll need to provide more info as to what you want to do, though, for my answer to be more specific.

Related

how to make array like this

I have an array in the array, and I want to make it just one array, and I can easily retrieve that data
i have some like
this
but the coding only combines the last value in the first array, not all values
is it possible to make it like that?
so that I can take arrays easily
I would make use of the unpacking operator ..., combined with array_merge:
$array['test2'] = array_merge(...array_merge(...$array['test2']));
In your case you need to flatten exactly twice, if you try to do it one time too much it will fail due to the items being actual arrays themselves (from PHP's perspective).
Demo: https://3v4l.org/npnTi
Use array_merge (doc) and ... (which break array to separate arrays):
function flatten($arr) {
return array_merge(...$arr);
}
$arr = [[["AAA", "BBB"]], [["CCC"]]];
$arr = flatten(flatten($arr)); // using twice as you have double depth
In your case, $arr is $obj["test2"]. If your object is json cast it to array first and if it is a string use json_decode
Live example: 3v4l
if you have a array then you can use the below code
if(!empty($array['test2'])){
$newarray = array();
foreach ($array['test2'] as $arrayRow) {
$newarray = array_merge($newarray,$arrayRow);
}
$array['test2'] = $newarray;
}

PHP - How to test a multidimensional array for duplicate element values in any order

I'm not sure the title really gets across what I'm asking, so here's what I'm trying to do:
I have an array of arrays with four integer elements each, ie.
Array(Array(1,2,3,4), Array(4,2,3,1), Array(18,3,22,9), Array(23, 12, 33, 55))
I basically need to remove one of the two arrays that have the same values in any order, like indices 0 and 1 in the example above.
I can do this pretty easily when there are only two elements to check, using the best answer code in this question.
My multidimensional array can have 1-10 arrays at any given time, so I can't seem to figure out the best way to process a structure like that and remove arrays that have the same numbers in any order.
Thanks so much!
I've been thinking about this, and I think using a well designed closure with array_filter might be the way I'd go about this:
$matches = array();
$array = array_filter($array, function($ar) use (&$matches) {
sort($ar);
if(in_array($ar, $matches)) {
return false;
}
$matches[] = $ar;
return true;
});
See here for an example: http://ideone.com/Zl7tlR
Edit: $array will be your final result, ignore $matches as it's just used during the filter closure.

Unset keys in an array with matching values in another array

How can I unset the keys in one array where the values contained in a second array match the values in the first array?
Actual array:
$fruits = array('Banana','Cherry','Orange','Apple');
Elements I want to remove:
$remove = array('Banana','Apple');
Need to return:
$array = array('Cherry','Orange');
I know it's possible to remove each one with unset, but I'm looking to make it in one line with two array.
Thanks.
Take a look at this function
link
$arrayWithoutTheDesiredElements = array_diff($originalArr, $toRemoveArray)
EDIT:
for your case: $array = array_diff($fruits, $remove);

Swap my element's order to be the first in an array

Let's say I have an array like so:
array(
[0]=>1
[1]=>3
[3]=>5
[15]=>6
);
Arbitrarily I want array[15] to be the first:
array(
[15]=>6
[0]=>1
[1]=>3
[3]=>5
);
What is the fastest and most painless way to do this?
Here are the things I've tried:
array_unshift - Unfortunately, my keys are numeric and I need to keep the order (sort of like uasort) this messes up the keys.
uasort - seems too much overhead - the reason I want to make my element the first in my array is to specifically avoid uasort! (Swapping elements on the fly instead of sorting when I need them)
Assuming you know the key of the element you want to shift, and that element could be in any position in the array (not necessarily the last element):
$shift_key = 15;
$shift = array($shift_key => $arr[$shift_key]);
$arr = $shift + $arr;
See demo
Updated - unset() not necessary. Pointed out by #FuzzyTree
You can try this using a slice and a union operator:
// get last element (preserving keys)
$last = array_slice($array, -1, 1, true);
// put it back with union operator
$array = $last + $array;
Update: as mentioned below, this answer takes the last key and puts it at the front. If you want to arbitrarily move any element to the front:
$array = array($your_desired_key => $array[$your_desired_key]) + $array;
Union operators take from the right and add to the left (so the original value gets overwritten).
If #15 is always last you can do
$last = array_pop($array); //remove from end
array_unshift($last); //push on front
To reorder the keys for sorting simply add
$array = array_values($array); //reindex array
#Edit - if we don't assume its always last then I would go with ( if we always know wwhat the key is, then most likely we will know its position or it's not a numerically indexed array but an associative one with numeric keys, as op did state "arbitrarily" so one has to assume the structure of the array is known before hand. )
I also dont see the need to reindex them as the op stated that it was to avoid sorting. So why would you then sort?
$item = $array[15];
unset($array[15]); //....etc.

How to find string elements in another string and remove them in PHP

By example:
FirstString='apple,gold,nature,grass,class'
SecondString='gold,class'
the Result must be :
ResultString='apple,nature,grass'
$first = explode(',',$firstString);
$second = explode(',',$secondString);
Now you have arrays and you can do whatever you want with them.
$result = array_diff($first, $second);
this is the easy way (for sure there must be more efficient ones):
First of all, you may want to separate those coma-separated strings and put them into an array (using the explode function):
$array1 = explode(',' $firstString);
$array2 = explode(',' $secondString);
Then, you can loop the first array and check whether it contents words of the second one using the in_array function (if so, delete it using the unset function):
// loop
foreach( $arra1 as $index => $value){
if( in_array ( $value , $array2 ) )
unset($array1[$index]); // delete that word from the array
}
Finally, you can create a new string with the result using the implode function:
$result = implode(',' , $array1);
That's it :D
I'm sure there is a function that can do it but you could always break up the strings and do a foreach on each one and do some string compares and build a new string. You could also break apart the second string and create a regular expression and do a preg_replace to replace the values in the string.

Categories