Change several ARRAY into new ARRAYS [duplicate] - php

This question already has answers here:
Combine arrays in PHP [duplicate]
(4 answers)
Closed 10 months ago.
I would like to know how to change the contents from several ARRAYS into new ARRAYS.
I have this 3 vars with a ARRAY each, lets say the first var is $number and it has this array:
Array
(
[0] => 1
[1] => 3
[2] => 9
)
The second var is $item and it has this:
Array
(
[0] => house
[1] => car
[2] => bike
)
And the third is $color and it has this:
Array
(
[0] => red
[1] => white
[2] => black
)
How can I change the contents and create new arrays like this:
Array
(
[0] => 1
[1] => house
[2] => red
)
Array
(
[0] => 3
[1] => car
[2] => white
)
Array
(
[0] => 9
[1] => bike
[2] => black
)

You can use array_map:
<?php
$number = [1,3,9];
$item = ['house','car','bike'];
$color = ['red','white','black'];
$res = array_map(null, $number, $item, $color);
print_r($res);
?>
which will output a single array of arrays that you want:
Array
(
[0] => Array
(
[0] => 1
[1] => house
[2] => red
)
[1] => Array
(
[0] => 3
[1] => car
[2] => white
)
[2] => Array
(
[0] => 9
[1] => bike
[2] => black
)
)

You can make a callback function with array_map() that returns each value together:
$result = array();
function merge_arrays($a,$b,$c){
return array($a,$b,$c);
}
$result = array_map("merge_arrays",$number,$item,$color);
DEMO

Related

PHP un-nest all element in multidimensional array [duplicate]

This question already has answers here:
How to "flatten" a multi-dimensional array to simple one in PHP? [duplicate]
(23 answers)
Closed 3 years ago.
I have a multidimensional array in PHP and I want to un-nest all elements to bring them to the top level. Here is the array:
Array
(
[0] => Array
(
[id] => 1
[color] => red
)
[1] => Array
(
[0] => Array
(
[id] => 2
[color] => blue
)
[1] => Array
(
[0] => Array
(
[id] => 3
[color] => green
)
)
[2] => Array
(
[id] => 4
[color] => blue
)
)
[2] => Array
(
[id] => 5
[color] => purple
)
)
What I want end the end is this... so basically it loops over the array and any group it just unnests it. Sorry, I don't know the proper terminology. Is there PHP function for this? I've tried several solutions on stack but it moves all key values pairs up to the top and not just the array groups --- it just creates a mess.
(
[0] => Array
(
[id] => 1
[id] => red
)
[1] => Array
(
[id] => 2
[color] => blue
)
[2] => Array
(
[id] => 3
[color] => green
)
[3] => Array
(
[id] => 4
[color] => blue
)
[4] => Array
(
[id] => 5
[color] => purple
)
)
Thanks!
You can do it like this, check the Demo
$result = [];
array_walk_recursive($array,function(&$v)use($result){
$result[] = $v;
});
$result = array_chunk($result,2);
$result = array_map(function($v){return array("id"=>$v[0],"color"=>$v[1]);});
print_r($result);
You can unpack it by using array_walk_recursive
$i = 0;
array_walk_recursive($a, function($v,$k)use(&$r,&$i){
$r[$i][$k] = $v;
($k == 'color') ? $i++ :$i;
});
print_r($r);
Working example :- https://3v4l.org/YPT2M
Use simple generic recursion as below(no id, no color),
function flattenArray($arr = [])
{
$retArr = [];
foreach ($arr as $val) {
if (is_array($val)) {
$retArr[] = array_filter($val, function ($v) {
return !is_array($v);
});
$retArr = array_merge(array_filter($retArr), flattenArray($val));
}
}
return $retArr;
}
$arr = flattenArray($arr);
Demo
Output:-
Array
(
[0] => Array
(
[id] => 1
[color] => red
)
[1] => Array
(
[id] => 2
[color] => blue
)
[2] => Array
(
[id] => 3
[color] => green
)
[3] => Array
(
[id] => 4
[color] => blue
)
[4] => Array
(
[id] => 5
[color] => purple
)
)

array unique make item disapear

I have this array :
Array
(
[0] => Array
(
[0] => Array
(
[0] => 10
[id_list] => 1
[id] => 1
)
[1] => Array
(
[0] => 11
[id_list] => 1
[id] => 1
)
[2] => Array
(
[0] => 12
[id_list] => 1
[id] => 1
)
)
[1] => Array
(
[0] => Array
(
[0] => 11
[id_list] => 2
[id] => 2
)
[1] => Array
(
[0] => 12
[id_list] => 2
[id] => 2
)
)
[2] => Array
(
[0] => Array
(
[0] => 13
[id_list] => 4
[id] => 4
)
)
)
and this code (where $dataListe is the result of a fetchAll query) :
$result = [];
foreach($dataListe as $listeDiff){
$result[] = $listeDiff;
}
// $resultUnique = array_unique($result);
echo "<pre>".print_r($result, true)."</pre>";
as you can see, there's some contact similar in my first and my second array (but contact can be the same in the 1st and the 3rd array, is I choose to add my contact in my 3rd array).
I want to remove the duplicate of each element in the general array.
But when I use array unique, I get this result :
Array
(
[0] => Array
(
[0] => Array
(
[0] => 10
[id_list] => 1
[id] => 1
)
[1] => Array
(
[0] => 11
[id_list] => 1
[id] => 1
)
[2] => Array
(
[0] => 12
[id_list] => 1
[id] => 1
)
)
)
Please I need help to only keep 1 item of each array at the end !
EDIT : I have almost the good result with the code below, but the id 12 is missing
$result = [];
foreach($dataListe as $listeDiff){
foreach($listeDiff as $contact){
if(!in_array($contact,$result)){
$result[] = $contact;
}
break;
}
}
As the PHP docs says :
Note: Note that array_unique() is not intended to work on multi dimensional arrays. (http://php.net/manual/en/function.array-unique.php)
You can try this solution
$uniqueResult = array_map("unserialize", array_unique(
array_map("serialize", $result)
));
as suggested by #daveilers on this question How to remove duplicate values from a multi-dimensional array in PHP.

Split an array into a MD array every nth line

bit of a question here. Ive got an array that contains data which has been parsed from a website using all our favourite php functions such as array_map.
The array is current 3 sub arrays deep.
Here is the code I am using:
for ($tcid = 1; $tcid <= count($categories); $tcid++) {
$catHeader[$tcid] = $categories[$tcid][0];
$event[$i]['tickets'] = $categories;
unset($categories[$tcid][0]);
$categories[$tcid] = array_map('trim', $categories[$tcid]);
$categories[$tcid] = array_values($categories[$tcid]);
$ab = 0;
for ($b = 0; $b <= count($categories[$tcid]); $b++) {
if ($categories[$tcid][$b] == "" || !$categories[$tcid][$b] || $categories[$tcid][$b] == null) {
unset($categories[$tcid][$b]);
}
}
}
and the array looks something like....
[1] => Array (
[data] => Array ( ...
)
[tickets] => Array (
[1] => Array (
[0] => xxx
[1] => etc
[3] => etc2
)
[2] => (
[0] => Std1
[1] => 10 / 10
[2] => £20.00
[3] => £200.00
[4] => Std2
[5] => 100 / 100
[6] => £13.00
[7] => £1,300.00
[8] => Std3
[9] => 10 / 320
[10] => £15.00
[11] => £150.00
)
)
)
My question to you today, is how on earth do I split the array every 4 \n's or array keys as they're known and explode each 4 into a further sub array?
So that Std1, Std2, Std3 will be their own sub array with its associated data of the 2nd key of tickets, but also doing this for every sub array of tickets that has more than 1 set of data (a set of data being 4 array keys).
I've tried all sorts but can't get it to work.
See below of how I want it to look.
[1] => Array (
[data] => Array ( ...
)
[tickets] => Array (
[1] => Array (
[0] => xxx
[1] => etc
[3] => etc2
)
[2] => (
[0] => Array (
[0] => Std1
[1] => 10 / 10
[2] => £20.00
[3] => £200.00
)
[1] => Array (
[0] => Std2
[1] => 100 / 100
[2] => £13.00
[3] => £1,300.00
)
[2] => Array (
[0] => Std3
[1] => 10 / 320
[2] => £15.00
[3] => £150.00
)
)
)
)
Thanks
As noted in the comments, you'd be best off handling your array by-reference to modify it's original contents somewhere within your loops
Provided the array groupings you want to chunk are in groups of 4, you could array_chunk() it:
$array['tickets'][2] = array_chunk($array['tickets'][2], 4);

How can I get random data from a multidimensional array? [duplicate]

This question already has answers here:
multi dimensional array in random order
(4 answers)
Closed 6 years ago.
Is it possible to get random data from an array?
See My Array:
Array
(
[0] => Array
(
[0] => My Data
[1] => Airport
[2] => Md
)
[1] => Array
(
[0] => Live in fear
[1] => Science
[2] => Sc
)
[2] => Array
(
[0] => State History
[1] => Government
[2] => MP
)
[3] => Array
(
[0] => Real Estate
[1] => Other
[2] => Property
)
[4] => Array
(
[0] => Real State
[1] => Not Sure
[2] => NoData
)
)
I need this type of random output...
Array
(
[0] => Array
(
[0] => My Data
[1] => Airport
[2] => Md
)
[1] => Array
(
[0] => Real State
[1] => Not Sure
[2] => NoData
)
[2] => Array
(
[0] => My Data
[1] => Airport
[2] => Md
)
[3] => Array
(
[0] => State History
[1] => Government
[2] => MP
)
[4] => Array
(
[0] => Live in fear
[1] => Science
[2] => Sc
)
)
Try the following shuffle function.Hope it would help you.
function shuffle_assoc($list) {
if (!is_array($list)) return $list;
$keys = array_keys($list);
shuffle($keys);
$random = array();
foreach ($keys as $key) {
$random[] = $list[$key];
}
return $random;
}
$arr = array();
$arr[] = array('id' => 50, 'foo' => 'hello');
$arr[] = array('id' => 17, 'foo' => 'byebye');
$arr[] = array('id' => 19, 'foo' => 'foo');
print_r(shuffle_assoc($arr));
You could simply use shuffle()
bool shuffle ( array &$array )
This function shuffles (randomizes the order of the elements in) an array. It uses a pseudo random number generator that is not suitable for cryptographic purposes.
shuffle($array); // Shuffles your array keys randomly every time.
shuffle() will be a better option in getting out the random value from multi dimensional array.
Reference: http://php.net/manual/en/function.shuffle.php
shuffle() Example:
The shuffle() function randomizes the order of the elements in the array.
This function assigns new keys for the elements in the array. Existing keys will be removed
<?php
$my_array = array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow","e"=>"purple");
shuffle($my_array);
print_r($my_array);
?>
Output:
Array ( [0] => red [1] => yellow [2] => green [3] => blue [4] => purple )
//The Output will keep shuffling if you refresh the browser.

Array sorting question

So I have an array such as this one:
Array
(
[-1] => Array
(
[3] => 3
[1] => 1
[6] => 6
[7] => 7
[5] => 5
)
)
It also contains some other keys that should not be modified.
I'd like to the numbers which are in a second array to come first (in the order of that second array), and then will be the numbers that don't exist in the second array, if any.
So for that matter, the second array would be:
Array
(
[0] => 6
[1] => 5
[2] => 3
)
And the final array should be as follows (please remember, there are some more keys inside of that array that should stay as they are):
Array
(
[-1] => Array
(
[6] => 6
[5] => 5
[3] => 3
[1] => 1
[7] => 7
)
)
Any ideas how that can be done?
Thanks!
It's not and shouldn't be termed as sorting but may be this code snippet may help you do what you want to:
$a1 = Array ( [-1] => Array ( [3] => 3 [1] => 1 [6] => 6 [7] => 7 [5] => 5 ) );
$a2 = Array ( [0] => 6 [1] => 5 [2] => 3 );
$sorted = getSortedArray($a1[-1] , $array2);
function getSortedArray($array1 , $array2){
$temp = Array();
$count = 0;
$totalKeys = sizeof($array2);
for($i=0;$i<sizeof($array2);$i++){
$temp[i] = $array1[$array2[i]];
unset($array1[$array2[i]]);
}
while($count!=sizeof($array1))
$temp[$totalKeys++] = $array1[$count++];
return $temp;
}
I believe the function you're looking for is called array_multisort().
array_multisort() can be used to sort
several arrays at once, or a
multi-dimensional array by one or more
dimensions.

Categories