Php Array removing duplication and string conversion - php

hi i have output of an array as follow:
Array (
[0] => 66, 65, 64
[1] => 57
[2] => 66,23
[3] => 66
)
How can i remove duplication values and convert the collection into comma separated string? The unique output is 66,65,64,57,23. Thanks

Make use of array_unique() and array_reverse():
$array = Array (
0 => '66, 65, 64',
1 => '57',
2 => '66,23',
3 => '66',
);
$collection = array();
foreach($array as $numbers) {
$nums = explode(',', $numbers);
foreach($nums as $num) {
$collection[] = trim($num);
}
}
// unique and sort
$collection = array_unique($collection, SORT_NUMERIC);
// reverse it so that it can be descending order
$collection = array_reverse($collection);
print_r($collection);
which will output :
Array (
[0] => 66
[1] => 65
[2] => 64
[3] => 57
[4] => 23
)

you iterate through the array and add it to a final array by checking its values then implode to construct a string.
$array = Array (
0 => array(66, 65, 64),
1 => array(57),
2 => array(66,23),
3 => array( 66)
);
$final = array();
foreach ($array as $item) {
foreach ($item as $num) {
if (!in_array($num, $final)) $final[] = $num;
}
}
$str = implode(",", $final);
echo $str

well, the code is lil ugly...
$test = [
'0' => '66, 65',
'1' => '80', '66'
];
$temp = implode(',', array_map('trim', array_unique(explode(',', implode(',', $test)))));
print_r($test);
print_r($temp);
//output
Array (
[0] => 66, 65
[1] => 80
[2] => 66
)
66,65,80

Ok:
<?php
$array = array(
"66, 65, 64",
57,
"66,23",
66
);
function dosplit($a,$b) {
if (preg_match("/,/",$b)) {
$a = array_merge($a, preg_split('/\s*,\s*/', $b));
} else {
array_push($a, $b);
}
return $a;
}
$result = array_reduce($array, 'dosplit' ,array());
$array = array_unique($result);
The output is:
Array
(
[0] => 66
[1] => 65
[2] => 64
[3] => 57
[5] => 23
)

This might is useful for you:
$array = array(
"66, 65, 64 ",
"57",
"66,23",
"66",
);
echo "<pre>";
print_r($array);
//to make single line
foreach ($array as $val) {
$singleline.=$val . ",";
}
echo $singleline . "</br>";
//remove the "," end of the value
$endvlaue = rtrim($singleline, ",");
echo $endvlaue;
//make an array
$val = explode(",", $endvlaue);
echo "<pre>";
print_r($val);
echo "<pre>";
//make uniqu
$finalvalue = array_unique($val);
echo "<pre>";
//make , seperator
print_r(implode(",", $finalvalue));

Related

Combine two arrays together

I have an array that looks like this:
array
(
[name] => name
[description] => description here
[first] => Array
(
[0] => weight
[1] => height
)
[second] => Array
(
[0] => 20 kg
[1] => 50 cm
)
[company_id] => 1
[category_id] => 7
)
what function will allow me to combine these into something that looks like the following?
array
(
[together]
(
[0] => weight 20kg
[1] => height 50cm
)
)
Update
For that current array you need to use the loop.
$first = $second = array();
foreach($yourArray as $key => $array) {
if(in_array($key, array('first', 'second')) {
$first[] = $array[0];
$second[] = $array[1];
}
}
$final['together'] = array($first, $second);
According to the first array
You can try this -
$new = array(
'together' => array(
implode(' ', array_column($yourArray, 0)), // This would take out all the values in the sub arrays with index 0 and implode them with a blank space
implode(' ', array_column($yourArray, 1)), // Same as above with index 1
)
);
array_column is supported PHP >= 5.5
Or you can try -
$first = $second = array();
foreach($yourArray as $array) {
$first[] = $array[0];
$second[] = $array[1];
}
$final['together'] = array($first, $second);
you also can try array_map as below
function merge($first,$second)
{
return $first ." ".$second;
}
$combine = array_map('merge', $yourArray[0],$yourArray[1]);

Getting specidic values from PHP arrays

Is there a way to get the first value from array, then the first value key + 3 ; then +6 then + 9 ans so on
Take this array for example,
array(1,2,5,14,19,2,11,3,141,199,52,24,16)
i want extract a value every 3 so the result would be
array(1,14,11,199,16)
Can i do that with existing PHP array function?
Use a for loop and increment the counter variable by 3.
for ($i = 0; $i <= count(your array); $i+3) {
echo $myarray[i]
}
The following is function that will handle extracting the values from a given array. You can specify the number of steps between each value and if the results should use the same keys as the original. This should work with regular and associative arrays.
<?php
function extractValues($array, $stepBy, $preserveKeys = false)
{
$results = array();
$index = 0;
foreach ($array as $key => $value) {
if ($index++ % $stepBy === 0) {
$results[$key] = $value;
}
}
return $preserveKeys ? $results : array_values($results);
}
$array = array(1, 2, 5, 14, 19, 2, 11, 3, 141, 199, 52, 24, 16);
$assocArray = array('a' => 1, 'b' => 2, 'c' => 5, 'd' => 14, 'e' => 19, 'f' => 2, 11, 3, 141, 199, 52, 24, 16);
print_r(extractValues($array, 3));
print_r(extractValues($array, 3, true));
print_r(extractValues($assocArray, 5));
print_r(extractValues($assocArray, 5, true));
?>
Output
Array
(
[0] => 1
[1] => 14
[2] => 11
[3] => 199
[4] => 16
)
Array
(
[0] => 1
[3] => 14
[6] => 11
[9] => 199
[12] => 16
)
Array
(
[0] => 1
[1] => 2
[2] => 52
)
Array
(
[a] => 1
[f] => 2
[4] => 52
)
Use a loop and check the key.
$result = array();
foreach($array as $key => $value) {
if ($key % 3 === 0) {
$result[] = $value;
}
}
Try below one:
<?php
$your_array = array (1,2,5,14,19,2,11,3,141,199,52,24,16);
$every_3 = array();
$i = 0;
foreach($your_value as $value) {
$i++;
if($i%3==0){
$every_3[]=$value;
}
}
var_dump($every_3);
?>
Do like this
$arr=array (1,2,5,14,19,2,11,3,141,199,52,24,16);
$narr=array();
for($i=0;$i<count($arr);$i=$i+3){
$narr[]=$arr[$i]
}
print_r($narr);
<?php
$mynums = array(1,2,5,14,19,2,11,3,141,199,52,24,16);
foreach ($mynums as $key => $value) {
if ( $key % 3 === 0)
{
$newnum[] = $value;
}
}
var_dump($newnum);
?>
$data = array(1,2,5,14,19,2,11,3,141,199,52,24,16);
$matches = array();
foreach($data as $key => $value)
{
if($key%3 === 0)
{
$matches[] = $value;
}
}
var_dump($matches);
The only way you could do it would be to use a loop, count the length of an array, and loop through using a % mathmatical operator.
It gives you a remainder of a division: http://au2.php.net/operators.arithmetic

combine arrays and concat value?

Little complex to explain , so here is simple concrete exemple :
array 1 :
Array
(
[4] => bim
[5] => pow
[6] => foo
)
array 2 :
Array
(
[n] => Array
(
[0] => 1
)
[m] => Array
(
[0] => 1
[1] => 2
)
[l] => Array
(
[0] => 1
[1] => 4
[2] => 64
)
And i need to output an array 3 ,
array expected :
Array
(
[bim] => n-1
[pow] => Array
(
[0] => m-1
[1] => m-2
)
[foo] => Array
(
[0] => l-1
[1] => l-4
[2] => l-64
)
Final echoing OUTPUT expected:
bim n-1 , pow m-1 m-2 ,foo l-1 l-4 l-64 ,
I tried this but seems pity:
foreach($array2 as $k1 =>$v1){
foreach($array2[$k1] as $k => $v){
$k[] = $k1.'_'.$v);
}
foreach($array1 as $res =>$val){
$val = $array2;
}
Thanks for helps,
Jess
CHALLENGE ACCEPTED
<?php
$a = array(
4 => 'bim',
5 => 'pow',
6 => 'foo',
);
$b = array(
'n' => array(1),
'm' => array(1, 2),
'l' => array(1, 4, 64),
);
$len = count($a);
$result = array();
$aVals = array_values($a);
$bKeys = array_keys($b);
$bVals = array_values($b);
for ($i = 0; $i < $len; $i++) {
$combined = array();
$key = $aVals[$i];
$prefix = $bKeys[$i];
$items = $bVals[$i];
foreach ($items as $item) {
$combined[] = sprintf('%s-%d', $prefix, $item);
};
if (count($combined) === 1) {
$combined = $combined[0];
}
$result[$key] = $combined;
}
var_dump($result);
?>
Your code may be very easy. For example, assuming arrays:
$one = Array
(
4 => 'bim',
5 => 'pow',
6 => 'foo'
);
$two = Array
(
'n' => Array
(
0 => 1
),
'm' => Array
(
0 => 1,
1 => 2
),
'l' => Array
(
0 => 1,
1 => 4,
2 => 64
)
);
You may get your result with:
$result = [];
while((list($oneKey, $oneValue) = each($one)) &&
(list($twoKey, $twoValue) = each($two)))
{
$result[$oneValue] = array_map(function($item) use ($twoKey)
{
return $twoKey.'-'.$item;
}, $twoValue);
};
-check this demo Note, that code above will not make single-element array as single element. If that is needed, just add:
$result = array_map(function($item)
{
return count($item)>1?$item:array_shift($item);
}, $result);
Version of this solution for PHP4>=4.3, PHP5>=5.0 you can find here
Update: if you need only string, then use this (cross-version):
$result = array();
while((list($oneKey, $oneValue) = each($one)) &&
(list($twoKey, $twoValue) = each($two)))
{
$temp = array();
foreach($twoValue as $item)
{
$temp[] = $twoKey.'-'.$item;
}
$result[] = $oneValue.' '.join(' ', $temp);
};
$result = join(' ', $result);
As a solution to your problem please try executing following code snippet
<?php
$a=array(4=>'bim',5=>'pow',6=>'foo');
$b=array('n'=>array(1),'m'=>array(1,2),'l'=>array(1,4,64));
$keys=array_values($a);
$values=array();
foreach($b as $key=>$value)
{
if(is_array($value) && !empty($value))
{
foreach($value as $k=>$val)
{
if($key=='n')
{
$values[$key]=$key.'-'.$val;
}
else
{
$values[$key][]=$key.'-'.$val;
}
}
}
}
$result=array_combine($keys,$values);
echo '<pre>';
print_r($result);
?>
The logic behind should be clear by reading the code comments.
Here's a demo # PHPFiddle.
//omitted array declarations
$output = array();
//variables to shorten things in the loop
$val1 = array_values($array1);
$keys2 = array_keys($array2);
$vals2 = array_values($array2);
//iterating over each element of the first array
for($i = 0; $i < count($array1); $i++) {
//if the second array has multiple values at the same index
//as the first array things will be handled differently
if(count($vals2[$i]) > 1) {
$tempArr = array();
//iterating over each element of the second array
//at the specified index
foreach($vals2[$i] as $val) {
//we push each element into the temporary array
//(in the form of "keyOfArray2-value"
array_push($tempArr, $keys2[$i] . "-" . $val);
}
//finally assign it to our output array
$output[$val1[$i]] = $tempArr;
} else {
//when there is only one sub-element in array2
//we can assign the output directly, as you don't want an array in this case
$output[$val1[$i]] = $keys2[$i] . "-" . $vals2[$i][0];
}
}
var_dump($output);
Output:
Array (
["bim"]=> "n-1"
["pow"]=> Array (
[0]=> "m-1"
[1]=> "m-2"
)
["foo"]=> Array (
[0]=> "l-1"
[1]=> "l-4"
[2]=> "l-64"
)
)
Concerning your final output you may do something like
$final = "";
//$output can be obtained by any method of the other answers,
//not just with the method i posted above
foreach($output as $key=>$value) {
$final .= $key . " ";
if(count($value) > 1) {
$final .= implode($value, " ") .", ";
} else {
$final .= $value . ", ";
}
}
$final = rtrim($final, ", ");
This will echo bim n-1, pow m-1 m-2, foo l-1 l-4 l-64.

Explode string in PHP that contain brackets and semicolon

Problem:
I have a string that looks like this:
[1=>2,3,4][5=>6,7,8][9=>10,11,12][13=>14,15][16=>17,18]
Question:
How can you get that string into this?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
I will try with:
$input = '[1=>2,3,4][5=>6,7,8][9=>10,11,12][13=>14,15][16=>17,18]';
$output = array();
preg_match_all('\[(\d+)=>([\d,]+)\]', $input, $matches);
foreach ($matches as $group) {
$output[$group[1])] = explode(',', $group[2]);
}
// and print result out:
foreach ( $output as $key => $val ) {
echo $key . '<br/>';
foreach ( $val as $v ) {
echo ' ' . $v . '<br/>';
}
}
This code:
$input = '[1=>2,3,4][5=>6,7,8][9=>10,11,12][13=>14,15][16=>17,18]';
$regex = '~\[(?P<keys>\d)+=>(?P<values>(?:\d+,?)+)\]~';
$result = array();
if (preg_match_all($regex, $input, $matches)) {
foreach ($matches['keys'] as $key => $value) {
$result[$value] = explode(',', $matches['values'][$key]);
}
}
print_r($result);
Results to this:
Array
(
[1] => Array
(
[0] => 2
[1] => 3
[2] => 4
)
[5] => Array
(
[0] => 6
[1] => 7
[2] => 8
)
[9] => Array
(
[0] => 10
[1] => 11
[2] => 12
)
[3] => Array
(
[0] => 14
[1] => 15
)
[6] => Array
(
[0] => 17
[1] => 18
)
)
$str = "[1=>2,3,4][5=>6,7,8][9=>10,11,12][13=>14,15][16=>17,18]";
$str = explode("]", $str);
$finalResult = array();
foreach ($str as $element) {
if (!empty($element)) {
$element = substr($element, 1);
$element = explode("=>", $element);
// element[0] contains the key
$element[1] = explode(",", $element[1]);
$finalResult[$element[0]] = $element[1];
}
}
print_r($finalResult);
<?php
$str = "[1=>2,3,4][5=>6,7,8][9=>10,11,12][13=>14,15][16=>17,18]";
$parts1 = explode("][",$str);
$parts1[0]=str_replace("[","",$parts1[0]);
$parts1[count($parts1)-1]=str_replace("]","",$parts1[count($parts1)-1]);
foreach($parts1 as $k=>$v){
$parts2[]=explode("=>",$v);
}
foreach($parts2 as $k=>$v){
echo "<div>".$v[0]."</div>";
foreach(explode(",",$v[1]) as $key=>$value){
echo "<div style='margin-left:20px'>".$value."</div>";
}
}
Output Would be
Using only str_replace():
$dict = array(
'=>' => "\n\t",
',' => "\n\t",
'][' => "\n",
'[' => '',
']' => '',
);
echo str_replace(array_keys($dict), array_values($dict), $str);
Will give the result you want.

php - sort by value of last key in array?

I'm trying to figure out how to sort an array by the value of the last key, when the number of keys are unknown?
So, if I have arrays that look like this:
Array(
[0] => Array(
[0] => Bob
[1] => A
[2] => Parker
)
[1] => Array(
[0] => John
[1] => Smith-Doe
)
[2] => Array(
[0] => Giuseppe
[1] => Gonzalez
[2] => Octavio
[3] => Hernandez
)
)
I want to sort it by the last value in the array:
Giuseppe Gonzalez Octavio Hernandez
Bob A. Parker
John Smith-Doe
$arr = array(
array('Bob', 'A', 'Parker'),
array('John', 'Smith-Doe'),
array('Giuseppe', 'Gonzalez', 'Octavio', 'Hernandez')
);
usort($arr, 'sort_by_last_item');
var_dump($arr);
function sort_by_last_item($a, $b)
{
return end($a) > end($b);
}
or if you're using php 5.3:
$arr = array(
array('Bob', 'A', 'Parker'),
array('John', 'Smith-Doe'),
array('Giuseppe', 'Gonzalez', 'Octavio', 'Hernandez')
);
usort($arr, function($a, $b) { return end($a) > end($b); });
var_dump($arr);
$data = array( /* your data */ );
$output = array();
foreach ( $data as $v ) {
$output[ end($v) ] = $v;
}
ksort($output);
var_dump($output);
alternatively:
$data = array( /* your data */ );
$output = array();
foreach ( $data as $v ) {
$key = implode(' ', array_reverse($v));
$output[ $key ] = $v;
}
ksort($output);
var_dump($output);
Second method allow you to have many records with the same last element and sorts by last elements, and if they are equals - sort by first before last and so on...
This works:
function array_last_item_sort($array){
$return = array();
$sort = array();
foreach($array as $i => $item){
$sort[$i] = $item[count($item) - 1];
}
asort($sort);
foreach($sort as $i => $value){
$return[] = $array[$i];
}
return $return;
}

Categories