Move an element to first position in an array - php

here is my array:
Array
(
[0] => Array
(
[id] => 8
[title] => MUSIC
)
[1] => Array
(
[id] => 17
[title] => Indie
)
[2] => Array
(
[id] => 14
[title] => SPORTS
)
[3] => Array // Need to move this on first position
(
[id] => 15
[title] => Hipster
)
[4] => Array
(
[id] => 16
[title] => Web Seriesdf
)
)
I want array with key [3] to be on first position and then the rest of the elements.
I tried array_merge and array_unshift. But not working

You just need to take only three steps.
- Copy n'th array in variable.
- Delete n'th index from array. using unset()
- Put variable at the 0th index of the array. Using array_unshift()
Step 1:
$array=$mainArray[N];
Step 2:
unset($mainArray[N]);
Step 3:
array_unshift($mainArray, $array);

Lets assume your array to be $x;
$new_value = $x[3];
unset($x[3]);
array_unshift($x,$new_value);
This shall solve your problem.

You can also use array_merge
<?php
$a = [1,2,3,4,5];
$new_value = [$a[1]];
unset($a[1]);
$c = array_merge($new_value,$a);
print_r($c);
?>
Check output : https://eval.in/590702

Use
$array = array('3' => $array['3']) + $array;
phpfiddle Preview and eval.in Preview
Note: im moving 2 in my array. In your method add 3
Example
$array = array(
'0' => array(
'id'=>'8',
'title'=>'MUSIC'
),
'1' => array(
'id'=> '17',
'title'=> 'Indie'
),
'2' => array(
'id'=>'14',
'title'=>'SPORTS',
),
'3' => array(
'id'=>'14',
'title'=>'SPORTS',
),
);
$array = array('2' => $array['2']) + $array;
print_r($array);
Output
Array ( [2] => Array ( [id] => 14 [title] => SPORTS ) [0] => Array ( [id] => 8 [title] => MUSIC ) [1] => Array ( [id] => 17 [title] => Indie ) [3] => Array ( [id] => 14 [title] => SPORTS ) )

Use array_unshift();
Please check below code.
<?php
$a = Array(
'0' => Array('id' => '8','title' => 'MUSIC'),
'1' => Array('id' => '17','title' => 'Indie'),
'2' => Array('id' => '14','title' => 'SPORTS'),
'3' => Array('id' => '15','title' => 'Hipster'),
'4' => Array('id' => '16','title' => 'Web Seriesdf')
);
echo '<pre>';print_r($a);
$a3 = $a['3'];
unset($a['3']);
array_unshift($a,$a3);
echo '<pre>';print_r($a);
?>
Check output - https://eval.in/590723

Related

Combining duplicate keys in a multidimensional array in PHP [duplicate]

This question already has answers here:
Group subarrays by one column, make comma-separated values from other column within groups
(2 answers)
Closed last month.
here's how it looks in the PHP code:
<?php
$array = array(
array(
'name' => 'filter_amount',
'value' => '100-ml'
),
array(
'name' => 'filter_amount',
'value' => '200-ml'
),
array(
'name' => 'page_size',
'value' => '7'
)
);
print_r($array);
?>
Example of print_r() function output:
Array
(
[0] => Array
(
[name] => filter_amount
[value] => 100-ml
)
[1] => Array
(
[name] => filter_amount
[value] => 200-ml
)
[2] => Array
(
[name] => page_size
[value] => 7
)
)
I need to combine duplicates of filter_amount values from the array.
The values of these duplicates must be commas separated and the result should be the following code:
Array
(
[0] => Array
(
[name] => filter_amount
[value] => 100-ml,200-ml
)
[1] => Array
(
[name] => page_size
[value] => 7
)
[2] => Array
(
[name] => orderby
[value] => rating
)
[3] => Array
(
[name] => paged
[value] => 1
)
)
Since you want value to be concatenated by a comma, you'll have to make a cycle of it
<?php
//Allow me to change this variable name, just to not create confusion
$content = array(
array(
'name' => 'filter_amount',
'value' => '100-ml'
),
array(
'name' => 'filter_amount',
'value' => '200-ml'
),
array(
'name' => 'page_size',
'value' => '7'
)
);
//$content is your initial array
//$outputArray is the final worked-up array
$outputArray = [];
//Let's make a cycle going for every array inside $content
foreach ($content as $innerArray) {
//Does this $innerArray['name'] (filter_ammount) exist in $outputArray in an array
//consisting in key => value where the key is 'name' and equals
//what we look for that is(filter_ammount)?
$key = array_search($innerArray['name'], array_column($outputArray , 'name'));
//If not, let's place this array in the $output array
if ($key === false) {
array_push($outputArray, $innerArray);
} else {
//If exists, then $key is the $key of the $outputArray and let's add to its value
//our current value, that is in our $innerArray, concatenated with a comma
$outputArray[$key]['value'] .= ",". $innerArray['value'];
}
}
//Boom, magic
print_r($outputArray);
//Note: This is going to affect every duplicate it finds, as in:
//If you got 3 arrays with name 'filter_ammount' and 2 arrays with name
//'page_size', it's going to concatenate the filter_ammount and the 'page_size'.
//If you specifically just want filter_ammount,
//replace this -> $key = array_search($innerArray['name'], array_column($outputArray , 'name'));
//with this -> $key = array_search('filter_ammount', array_column($outputArray , 'name'));
?>
References
http://php.net/manual/en/function.array-search.php
http://php.net/manual/en/function.array-column.php
How to combine two items by 2 duplicate columns?
[root#localhost TEST]# php R00.php
Array
(
[0] => Array
(
[0] => S01
[1] => 172.16.20.222
[2] => 10.10.10.100
[3] => 445
)
[1] => Array
(
[0] => S02
[1] => 10.10.10.10
[2] => 192.168.100.100
[3] => 22
)
[2] => Array
(
[0] => S03
[1] => 10.10.10.10
[2] => 192.168.100.100
[3] => 22
)
[3] => Array
(
[0] => S04
[1] => 172.16.20.222
[2] => 10.10.10.100
[3] => 23
)
[4] => Array
(
[0] => S05
[1] => 100.100.100.100
[2] => 192.168.100.100
[3] => 22
)
[5] => Array
(
[0] => S06
[1] => 192.168.200.10
[2] => 192.168.100.100
[3] => 22
)
[6] => Array
(
[0] => S07
[1] => 10.10.10.10
[2] => 192.168.100.100
[3] => 22
)
[7] => Array
(
[0] => S08
[1] => 192.168.100.100
[2] => 10.10.100.106
[3] => 446
)
[8] => Array
(
[0] => S09
[1] => 172.16.20.223
[2] => 10.10.10.108
[3] => 447
)
[9] => Array
(
[0] => S10
[1] => 192.168.100.100
[2] => 10.10.10.109
[3] => 448
)
)
[root#localhost TEST]#
combine 1 or 2 items by 2 column duplicate below is result I need
Array
(
[0] => Array
(
[0] => S01 , S04
[1] => 172.16.20.222
[2] => 10.10.10.100
[3] => 445 , 23
)
[1] => Array
(
[0] => S02 , S03 , S07
[1] => 10.10.10.10
[2] => 192.168.100.100
[3] => 22
)
[3] => Array
(
[0] => S05 , S06
[1] => 100.100.100.100 , 192.168.200.10
[2] => 192.168.100.100
[3] => 22
)
[4] => Array
(
[0] => S08
[1] => 192.168.100.100
[2] => 10.10.100.106
[3] => 446
)
[5] => Array
(
[0] => S09
[1] => 172.16.20.223
[2] => 10.10.10.108
[3] => 447
)
[6] => Array
(
[0] => S10
[1] => 192.168.100.100
[2] => 10.10.10.109
[3] => 448
)
)
Try this:
<?php
$array = array(
array(
'name' => 'filter_amount',
'value' => '100-ml'
),
array(
'name' => 'filter_amount',
'value' => '200-ml'
),
array(
'name' => 'page_size',
'value' => '7'
)
);
$tmp = array();
foreach($array as $val) {
$tmp[$val['name']]['values'][] = $val['value'];
}
foreach($tmp as $k => $v) {
$item = implode(',', array_unique(explode(',', implode(',',$v['values']))));
$newArr[] = array('name' => $k, 'value' => $item);
}
echo '<pre>';
print_r($newArr);
echo '</pre>';
got it with the following crazy mess:
$name = array_column($array, 'name');
$value = array_column($array, 'value');
foreach($name as $nk=>$nv)
foreach($value as $vk=>$vv)
if($nk == $vk)
$a[$nv][] = $vv;
foreach($a as $k=>$v)
$b[$k] = implode(',', $v);
$z = 0;
foreach($b as $k=>$v)
{
$c[$z]['name'] = $k;
$c[$z]['value'] = $v;
$z++;
}
$c is the resulting array
Or using a medley of array functions:
<?php
$array = array(
array(
'name' => 'filter_amount',
'value' => '100-ml'
),
array(
'name' => 'filter_amount',
'value' => '200-ml'
),
array(
'name' => 'page_size',
'value' => '7'
)
);
$names = array_column($array, 'name');
$values = array_column($array, 'value');
$result = [];
foreach (array_unique($names) as $k)
$result[$k] = implode(", ", array_filter($values,
function($v, $indx) use ($names, $k) {
return $names[$indx] == $k;
}, ARRAY_FILTER_USE_BOTH));
print_r($result);
$result2 = [];
foreach ($result as $k=>$v) $result2[] = ['name'=>$k, 'value'=>$v];
print_r($result2);
Results in:
Array
(
[filter_amount] => 100-ml, 200-ml
[page_size] => 7
)
Array
(
[0] => Array
(
[name] => filter_amount
[value] => 100-ml, 200-ml
)
[1] => Array
(
[name] => page_size
[value] => 7
)
)
All of the other answers up to now are using two or more iterating techniques for this task. There only needs to be one loop.
Build an associative output array based on the name values as you iterate. If the associative key isn't set, then save the whole row. If it is set, then just append a comma then the new value data to the stored value element.
Using temporary keys allows isset() to swiftly check for existence. It will always outperform array_search() and in_array() because of how php treats arrays (as hash maps).
Remove the temporary keys when the loop is finished by calling array_values().
Code: (Demo)
$result = [];
foreach ($array as $row) {
if (!isset($result[$row['name']])) {
$result[$row['name']] = $row;
} else {
$result[$row['name']]['value'] .= ',' . $row['value'];
}
}
var_export(array_values($result));
Output:
array (
0 =>
array (
'name' => 'filter_amount',
'value' => '100-ml,200-ml',
),
1 =>
array (
'name' => 'page_size',
'value' => '7',
),
)

add items to multidimensional array programmatically in php

I have the following array
$a = array(0 => 'Item',
1 => 'Wattles',
2 => 'Types',
3 => 'Compost',
4=> 'Estimated',
5 => '123',
6 => 'Actual',
7 => '12',
);
That is sorted with the following code.
echo "<pre>";
print_r($a);
$a_len = count($a);
$fnl = array();
$i = 0;
while($i<$a_len){
$fnl[$a[$i]] = $a[++$i];
$i++;
}
print_r($fnl);
It prints correctly
Array
(
[Item] => Wattles
[Types] => Compost
[Estimated Qty] => 123
[Actual Qty] => 12
)
until i add multiple entries.
Array
(
[0] => Item
[1] => Wattles
[2] => Types
[3] => Compost
[4] => Estimated Qty
[5] => 123
[6] => Actual Qty
[7] => 12
[8] => Item
[9] => Silt Fence
[10] => Types
[11] => Straw
[12] => Estimated Qty
[13] => 45
[14] => Actual Qty
[15] => 142
)
I need to make this add items in a multidimensional array.
$items = array
(
array("Wattles","Silt Fence), //items
array("Compost","Straw"), //types
array(123,45), //estimated quantity
array(12,142) //actual quantity
);
There are a few given numbers. There are exactly 4 entries (8 items) before the list repeats itself.
I have been stuck on this portion for hours, and don't know how to get my code working as I want it to.
To get the expected result with string keys you can do:
foreach(array_chunk($a, 2) as $pairs) {
$result[$pairs[0]][] = $pairs[1];
}
Yields:
Array
(
[Item] => Array
(
[0] => Wattles
[1] => Silt Fence
)
[Types] => Array
(
[0] => Compost
[1] => Straw
)
[Estimated] => Array
(
[0] => 123
[1] => 45
)
[Actual] => Array
(
[0] => 12
[1] => 142
)
)
Then if you want it numerically indexed:
$result = array_values($result);
You have your structure for a multidimensional array wrong. You should construct your array like this:
$a = array(
0 => array(
'Item' => 'Wattles',
'Types' => 'Compost',
'Estimated' => 123,
'Actual' => 12
)
);
Then to add to it:
$a[] = array(
'Item' => 'Silt Fence',
'Types' => 'Straw',
'Estimated' => 45,
'Actual' => 142
);
Render it out to see the results which are what I think you are looking for.
print_r($a);
I can post a link if you want to learn how to sort multidimensional arrays by sub-array values if you need.

explode string to a multi array with 2 delimiter

I have this kind of sting i variable in php:
$hccRol = GA#COR,OP#COR,FOR#TB,GA#LTS,FOR#MOD,GA#PMAI,LDR#LID,HCC#LAD,HN#LAD,OP#LAD,GA#LAD,GA#WM,OP#WM,HN#WM,OP#VZ,HN#VZ,GA#VZAI
I want convert this to multi array that look somthing like this:
Array ( [GA] => Array ( [1] => COR
[2] => LTS
[3] => LAD
[4] => WM
[5] => VZAI
)
[FOR] => Array( [1] => TB
[2] => MOD
)
[OP] => Array( [1] => COR
[2] => WM
[3] => VZ
)
)
So the # determines in witch primary array the value must come
CBroe gave you the steps to do it the traditional way, so just for fun because I was bored:
parse_str(str_replace(array('#',','), array('[]=','&'), $hccRol ), $result);
print_r($result);
PHP >= 5.4.0:
parse_str(str_replace(['#',','], ['[]=','&'], $hccRol ), $result);
The following is a basic way to explode on the delimiting characters, iterate the data, and declare the new array structure. I will honor your desired output and start the keys at 1 instead of the standard 0.
Code: (Demo)
$hccRol = "GA#COR,OP#COR,FOR#TB,GA#LTS,FOR#MOD,GA#PMAI,LDR#LID,HCC#LAD,HN#LAD,OP#LAD,GA#LAD,GA#WM,OP#WM,HN#WM,OP#VZ,HN#VZ,GA#VZAI";
foreach (explode(",", $hccRol) as $item) {
$halves = explode("#", $item, 2);
if (!isset($result[$halves[0]])) {
$result[$halves[0]][] = null; // add zero key placeholder element
}
$result[$halves[0]][] = $halves[1];
unset($result[$halves[0]][0]); // remove the placeholder element
}
var_export($result);
Output:
array (
'GA' =>
array (
1 => 'COR',
2 => 'LTS',
3 => 'PMAI',
4 => 'LAD',
5 => 'WM',
6 => 'VZAI',
),
'OP' =>
array (
1 => 'COR',
2 => 'LAD',
3 => 'WM',
4 => 'VZ',
),
'FOR' =>
array (
1 => 'TB',
2 => 'MOD',
),
'LDR' =>
array (
1 => 'LID',
),
'HCC' =>
array (
1 => 'LAD',
),
'HN' =>
array (
1 => 'LAD',
2 => 'WM',
3 => 'VZ',
),
)
If you are happy to have the 0 indexes, then just remove the if{} block and the unset() line.

Remove duplicate elements off a multi-dimension array

I have an array contain this data
Array
(
[id] => Array
(
[0] => 1
[1] => 10
[2] => 4
)
[age] => Array
(
[0] => 1
[1] => 1
[2] => 2
)
)
Now I want to remove duplicates from the ['age'] and leave the first one in tact.
So this would return
Array
(
[id] => Array
(
[0] => 1
[2] => 4
)
[age] => Array
(
[0] => 1
[2] => 2
)
)
Any ideas? Or is there a function already in place to do this?
Like Gordon said, you'd need a custom function to make the relationship but you can use http://php.net/manual/en/function.array-unique.php ?
Wouldn't it be better to have the keys of the age array the corresponding values of the id array?
<?php
$array = array(
'id' => array(0 => 1, 1 => 10, 3 => 4),
'age' => array(0 => 1, 1 => 1, 2 => 2)
);
array_walk($array, 'dupe_killer');
print_r($array);
function dupe_killer(&$value, $key)
{
$value = array_unique($value);
}
?>
You could try this
$array = array('id' => array(1,10,4), 'age'=>array(1,1,2));
$age_array = array();
foreach ($array['age'] as $key => $val) {
if (in_array($val, $age_array))
unset($array['id'][$key], $array['age'][$key]);
$age_array[] = $val;
}
print_r($array);
this returns Array ( [id] => Array ( [0] => 1 [2] => 4 ) [age] => Array ( [0] => 1 [2] => 2 ) )
Regards
Luke

How to sort multiple arrays in PHP

i have wrote a script to produce an array of data but now want to display in order of score. The array outputs as follows;
[display_name] => Array
(
[0] => ACT_Web_Designs
[1] => user1_design
[2] => user2_design
)
[proffesion] => Array
(
[0] => Web Developer
[1] => web developer
[2] => Web Developer
)
[score] => Array
(
[0] => 15
[1] => 6
[2] => 15
)
[img] => Array
(
[0] => ./?0000=gif&0001=3fadb8c362ff39f3322909899ff14760&0002=prof_pic
[1] =>
[2] =>
)
so in a nutshell I am wanting it to be converted as follows;
[display_name] => Array
(
[0] => ACT_Web_Designs
[1] => user2_design
[2] => user1_design
)
[proffesion] => Array
(
[0] => Web Developer
[1] => web developer
[2] => Web Developer
)
[score] => Array
(
[0] => 15
[1] => 15
[2] => 6
)
[img] => Array
(
[0] => ./?0000=gif&0001=3fadb8c362ff39f3322909899ff14760&0002=prof_pic
[1] =>
[2] =>
)
I have been looking at asort() but cant get anything to work. any help would be much appreciated.
This is exactly where the PHP's array_multisort comes to use. It is a case where you want to sort many arrays based on the comparison happening in just one of them.
I've modified the array score to have distinct values.
<?php
$arr = array(
'display_name' => array('ACT_Web_Designs','user1_design','user2_design'),
'proffesion' => array('Web Developer','web developer','web developer'),
'score' => array(12,6,15),
'img' => array('./?0000=gif&0001=3fadb8c362ff39f3322909899ff14760&0002=prof_pic','','')
);
var_dump($arr);
array_multisort($arr['score'], SORT_ASC, SORT_NUMERIC,
$arr['display_name'],
$arr['proffesion'],
$arr['img']
);
var_dump($arr);
?>
Here goes a working demo.
How about this simpler one
$arr = array("k"=>array("A","B","C"),"l"=>array(15,6,15),"n"=>array("k","l","n"));
array_multisort($arr["k"],SORT_NUMERIC,SORT_DESC,$arr["l"],$arr["n"]);
var_dump($arr);
Doesn't it work to just rsort the score array?
rsort($data['score'], SORT_NUMERIC);
I have managed to do this, i was just after a more efficient way;
$array = array(
'display_name' => array(0 => 'ACT_Web_Designs', 1 => 'user1_design', 2 => 'user2_design' ),
'proffesion' => array( 0 => 'Web Developer', 1 => 'web developer', 2 => 'Web Developer' ),
'score' => array( 0 => 15, 1 => 6, 2 => 15 ),
'img' => array( 0 => './?0000=gif&0001=3fadb8c362ff39f3322909899ff14760&0002=prof_pic', 1 => '', 2 => '' )
);
arsort($array['score'], SORT_NUMERIC );
foreach($array['score'] as $key => $val ) {
$newarray['display_name'][] = $array['display_name'][$key];
$newarray['proffesion'][] = $array['proffesion'][$key];
$newarray['score'][] = $array['score'][$key];
$newarray['img'][] = $array['img'][$key];
}
print_r($newarray);
returns
Array
(
[display_name] => Array
(
[0] => ACT_Web_Designs
[1] => user2_design
[2] => user1_design
)
[proffesion] => Array
(
[0] => Web Developer
[1] => Web Developer
[2] => web developer
)
[score] => Array
(
[0] => 15
[1] => 15
[2] => 6
)
[img] => Array
(
[0] => ./?0000=gif&0001=3fadb8c362ff39f3322909899ff14760&0002=prof_pic
[1] =>
[2] =>
)
)
Use rsort()
<?php
$fruits = array("lemon", "orange", "banana", "apple");
rsort($fruits);
reset($fruits);
while (list($key, $val) = each($fruits)) {
echo "$key = $val\n";
}
?>
This example would display:
0 = orange
1 = lemon
2 = banana
3 = apple
The most elegant solution that I could find would not reorder the data structure but merely access it in a different fashion.
$scores = $data['score'];
arsort($scores);
$keys_ordered_by_score = array_keys($scores);
Now you can, say, grab the display_name and "proffesion" that has the highest score by the following:
$first_place = $keys_ordered_by_score[0];
echo $data['display_name'][$first_place],
' is a ', $data['proffesion'][$first_place];
Of course, if you really need to reorder the data structure, this idea is useless to you. Any of the other answers using array_multisort() will likely suit that need.
This will not re-sort them for you, but it will let you go through them in the order you want. You can reassign them if you want, but I'd just use this for the output order.
Edit: This will not work, due to the possibility of non-unique key values. See Comments below, and learn from my mistake
$sort_order = $array['score'];
arsort($sort_order);
$sort_order = array_flip($sort_order);
foreach($sort_order as $key){
echo $array['display_name'][$key].' - '.$array['score'][$key];
}

Categories