2 different array with different values - php

My question may sound abit silly, but I know it is possible to do. I'm actually trying to make the array from mysql to be different from the array I have shuffle it already. I want to maintain the array keys, just the value in different order.
Here is the example,
Array from MYSQL:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
)
Array after shuffle:
Array
(
[0] => 3
[1] => 7
[2] => 8
[3] => 4
[4] => 1
[5] => 2
[6] => 5
[7] => 6
)
If you notice, MYSQL array key 3 has the same value as shuffle array, I want it to be different. How can I do so?
Here is my code:
function get_random_elements($array) {
$ori_array = $array;
echo "<pre>";
print_r($ori_array);
echo "</pre>";
shuffle($array);
echo "<pre>";
print_r($array);
echo "</pre>";
for($x=0; $x<count($array); $x++) {
if ($array[$x] == $ori_array[$x])
{
$dupliarray[] = "Array value: ".$array[$x]." Key :".$x;
unset($array[$x]);
}
}
echo "<pre>";
print_r($dupliarray);
echo "</pre>";
}
$mysql_array = array(0=>'1',1=>'2',2=>'3',3=>'4',4=>'5',5=>'6',6=>'7',7=>'8');
get_random_elements($mysql_array);

One solution can be to shuffle array until it became totally differ from source array:
$sourceArray = [0, 1, 2, 3, 4, 5, 6, 7, 8];
$shuffledArray = $sourceArray; //because function shuffle will change passed array
shuffle($shuffledArray);
while (count(array_intersect_assoc($sourceArray, $shuffledArray))) {
shuffle($shuffledArray);
}
echo '<pre>';
var_dump($sourceArray, $shuffledArray);

I suggest this variant: Code in sandbox
$startArray = [
0 => 1,
1 => 2,
2 => 3,
3 => 4,
4 => 5,
5 => 6,
6 => 7,
];
function getShuffledArray($startArray) {
$shuffledArray = [];
// save value of last element for situation when we have last 2 elements of start array and one of them - last
$lastElement = end($startArray);
while (count($startArray)) {
$candidateIndex = array_rand($startArray);
if ($candidateIndex == count($shuffledArray)) {
while ($candidateIndex == count($shuffledArray)) {
$candidateIndex = array_rand($startArray);
}
}
$shuffledArray[] = $startArray[$candidateIndex];
unset($startArray[$candidateIndex]);
// shuffle last two elements when one of them last (in start array)
if (count($startArray) == 2 && end($startArray) == $lastElement) {
$shuffledArray[] = end($startArray);
$shuffledArray[] = reset($startArray);
$startArray = [];
}
}
return $shuffledArray;
}
$shuffledArray = getShuffledArray($startArray);
print_r ($shuffledArray);

Related

Shift the position of each value to the next index In an associative array

I have an array in PHP.
For example :
Array
(
[3] => 6
[2] => 4
[1] => 2
[4] => 8
[6] => 12
)
I need to shift the position of each value to the next index.
ie, The desired output is
Array
(
[3] => 12
[2] => 6
[1] => 4
[4] => 2
[6] => 8
)
I need to keep the keys unchanged and round shift the values.
Which is the simplest method to attain it?
What I already tried is
$lastValue = $array[array_keys($array)[4]];
$firstKey = array_keys($array)[0];
for ($i=4; $i>0; $i--) {
$array[array_keys($array)[$i]] = $array[array_keys($array)[$i-1]];
}
$array[$firstKey] = $lastValue;
print_r($array);
php is so coool ^_^
part of the idea ~stolen~ taken from #Peters solution, sorry, mate :)
<?php
$array =
[
3 => 6,
2 => 4,
1 => 2,
4 => 8,
6 => 12,
];
$newArray = array_combine(array_keys($array), array_merge([array_pop($array)], $array));
var_dump($newArray);
demo
You can do a round shift on the value. Demo
$array =
[
3 => 6,
2 => 4,
1 => 2,
4 => 8,
6 => 12,
];
$values = [null];
$keys = [];
foreach($array as $k => $v){
$keys[] = $k;
$values[] = $v;
}
$values[0] = $v;
array_pop($values);
$result = array_combine($keys,$values);
print_r($result);

How to move values from 2nd array into the empty places of 1st array

How to move values from 2nd array into the empty places of 1st array
1st array as below
Array
(
[0] => 1
[1] =>
[2] => 4
[3] =>
)
2nd array as below
Array
(
[0] => 5
[1] => 9
)
I want output as merging 2nd array into 1st as shown below
Array
(
[0] => 1
[1] => 5
[2] => 4
[3] => 9
)
I have tried below code.....
for($i=0; $i<$count; $i++){
for($j=$i; $j<=$i; $j++)
if(empty($assign_taskk[$i])){
$assign_taskk[$i] = $taskkk[$i];
}
}
plz help me out for same
Lets say your arrays look like:
$a1 = [
0 => 1,
1 => null,
2 => 4,
3 => null,
];
$a2 = [
0 => null,
1 => 5,
2 => null,
3 => 9,
];
Then you can iterate over first array and add values from the second one when needed:
foreach ($a1 as $k => $v) {
if (empty($v) && !empty($a2[$k])) {
$a1[$k] = $a2[$k];
}
}
Another way to do it using below way-
<?php
$arr1= [1,null,4,null];
$arr2 = [null,5,null,9];
$result = array_values(array_filter($arr1) + array_filter($arr2));
print_r($result)
?>
DEMO: https://3v4l.org/R4aeE
Hi #amod try this
$_newArray = array_values(array_filter($array1) + array_filter($array2));
print_r($_newArray);
You can use below code for this:
$firstArray = [1,'',4,''];
$secondArray = [5,9];
$secondArrayCounter = 0;
foreach($firstArray as $key => $value) {
if (empty($value)) {
$firstArray[$key] = $secondArray[$secondArrayCounter];
$secondArrayCounter++;
}
}
print_r($firstArray);
Hope it helps you.

How to get data from variable array length?

I have this code:
$ItemID = 'a62442e2-ca1f-4fd1-b80d-0d0dc511758e';
$GET_FreeTextFields = new \Picqer\Financials\Exact\ItemExtraField($connection);
$FreeTextFields = $GET_FreeTextFields->filter("ItemID eq guid'$ItemID'", '', '' );
$FreeTextFields01 = array();
$FreeTextFields02 = array();
foreach($FreeTextFields as $GET_FreeTextFields){
$FreeTextFields01[] = $GET_FreeTextFields->Value;
$FreeTextFields02[] = $GET_FreeTextFields->Number;
}
print_r($FreeTextFields01);
print_r($FreeTextFields02);
This outputs:
Value Array
(
[0] => 390
[1] => 804715
[2] => WW001
[3] => WHT/WHT/WHT
[4] => 39/42
[5] => 804715 WW00139/42
[6] => 3pk Quarter Socks
)
Numbers Array
(
[0] => 3
[1] => 4
[2] => 5
[3] => 6
[4] => 7
[5] => 8
[6] => 10
)
What this needs to output:
What i want if i use the first output so with 6 values in the array:
$FreeTextField01 = null
$FreeTextField02 = null
$FreeTextField03 = 390
$FreeTextField04 = 804715
$FreeTextField05 = WW001
$FreeTextField06 = WHT/WHT/WHT
$FreeTextField07 = 39/42
$FreeTextField08 = 804715 WW00139/42
$FreeTextField09 = null
$FreeTextField10 = 3pk Quarter Socks
But with other $ItemID, it can also output:
Value Array
(
[0] => 10100153
[1] => 2007
[2] => 350
[3] => 804082
[4] => WW006
[5] => WHT/NNY/OXGM
[6] => 35/38
[7] => 804082 WW00635/38
[8] => 0,00138857
[9] => Champion 3pk Quarter Socks
)
Numbers Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
)
What i want is that if a variable is not in the numbers list so 1-10, setting it to empty, and if the numbers is in the numbers array setting that number to the corresponding value variable. For example the number at [0] is 1 then set the variable $FreeTextField1 to $NumbersArray[0]->Value.
I keep making all kinds off loops but i just get stuck at the fact that the array length changes so that [6] can be the number 10 at one $itemID, but at another $ItemID, the number can be 6.
I tried researching this but I don't even know what I have to type in google to find this problem, that's why I'm describing it here.
edit i tried describing it a second time:
Yeah I'm having problems describing what i want, so let me try again. I get two arrays as output one with numbers that correspond with place it stands, as example you have FreeTextField0 thru FreeTextField10. What i tried to do is if (Numbers[0] == 0){ $FreeTextField0 = Value[0]}, but then I get the problem that Numbers[0] can be 3 or something else because if FreeTextField1 is empty i don't get a null value but nothing.
What i want if i use the first output so with 6 values in the array:
$FreeTextField01 = null
$FreeTextField02 = null
$FreeTextField03 = 390
$FreeTextField04 = 804715
$FreeTextField05 = WW001
$FreeTextField06 = WHT/WHT/WHT
$FreeTextField07 = 39/42
$FreeTextField08 = 804715 WW00139/42
$FreeTextField09 = null
$FreeTextField10 = 3pk Quarter Socks
I think this is what you're after but I have to say that I think you're barking up the wrong tree here. You really should not dynamically create variables in your script. To me, it is a serious code-smell and I think you should evaluate your design here.
http://sandbox.onlinephpfunctions.com/code/b245a0218ce174e68508139872f394def5409b05
<?php
// Test case
$values = [
'390',
'804715',
'WW001',
'WHT/WHT/WHT',
'39/42',
'804715 WW00139/42',
'3pk Quarter Socks'
];
$numbers = [3, 4, 5, 6, 7, 8, 10];
// Flip the $numbers array and then use the keys to find the corresponding values in the $values array
$intersection = array_unique(array_intersect_key($values, array_flip($numbers)));
// Fill in the missing keys and use `null` as the value
$output = $intersection + array_fill_keys(range(1,10), null);
// Sort the final output by the keys
ksort($output);
// Format the keys to match FreeTextField{00}
$output = array_combine(
array_map(function($k){ return 'FreeTextField'.str_pad($k, 2, '0', STR_PAD_LEFT); }, array_keys($output)),
$output
);
// Use the extract function to bring all those array keys + values into the symbol table.
// You can now use $FreeTextField01 - $FreeTextField10
extract($output);
var_dump($output);
UPDATE
http://sandbox.onlinephpfunctions.com/code/244c4f1ed45db398c48b8330c402b375eb358446
<?php
// Test case
$input = [
['Value' => '390', 'Number' => 3],
['Value' => '804715', 'Number' => 4],
['Value' => 'WW001', 'Number' => 5],
['Value' => 'WHT/WHT/WHT', 'Number' => 6],
['Value' => '39/42', 'Number' => 7],
['Value' => '804715 WW00139/42', 'Number' => 8],
['Value' => '3pk Quarter Socks', 'Number' => 10],
];
$intersection = [];
foreach ($input as $config) {
$value = $config['Value'];
$number = $config['Number'];
$intersection[$number] = $value;
}
// Fill in the missing keys and use `null` as the value
$output = $intersection + array_fill_keys(range(1,10), null);
// Sort the final output by the keys
ksort($output);
// Format the keys to match FreeTextField{00}
$output = array_combine(
array_map(function($k){ return 'FreeTextField'.str_pad($k, 2, '0', STR_PAD_LEFT); }, array_keys($output)),
$output
);
// Use the extract function to bring all those array keys + values into the symbol table.
// You can now use $FreeTextField01 - $FreeTextField10
extract($output);
var_dump($output);
Use ${$var}
If you want to see a doc about this type of var you can see it here:
http://php.net/manual/en/language.variables.variable.php

Search array input key in array

How do I find the keys array of disciplines that have appropriate values?
For Example:
$arr1 = [2, 4, 12];
$result = [...] // Var_dump in link
in_array($arr1, $result);
Regardless of their order, I need to see if there is a set of keys or a no.
But in_array() does not work.
Thanks!
Dump array
Update (01.03.2017)
This is my version of the solution to this problem
$findResult = array_filter($result, function($val)use($get){
$requiredDisciplines = [1, $get['disciplines']['second'], $get['disciplines']['third'], $get['disciplines']['four']]; // запрос
$activePriorities = [];
foreach ($val['disciplines'] as $discipline) {
if (in_array($discipline['id'], $requiredDisciplines)) {
$activePriorities[] = $discipline['priority'];
}
}
for ($i = 0; $i<3; $i++){
if(!in_array($i, $activePriorities))
return false;
}
/*if(in_array(0, $activePriorities) && in_array(1, $activePriorities) && in_array(2, $activePriorities) != true)
return false;*/
// print_r($activePriorities);
return true;
});
I've got a versatile one-liner that will give you all of the arrays containing matches. (so you can derive the keys or the count from that). (demo)
This function is only set to compare the values between the needle and the haystack, but can be set to search keys-values pairs by replacing array_intersect with array_intersect_assoc and adding ,ARRAY_FILTER_USE_BOTH to the end of the filter function (reference: 2nd snippet # https://stackoverflow.com/a/42477435/2943403)
<?php
// haystack array
$result[]=array(1,2,3,4,5,6,7,8,9,10,11,12);
$result[]=array(1,3,5,7,9,11);
$result[]=array(2,4,6,8,10,12);
// needle array
$arr1=array(2,4,12);
//one-liner:
$qualifying_array=array_filter($result,function($val)use($arr1){if(count(array_intersect($val,$arr1))==count($arr1)){return $val;}});
/*
// multi-liner of same function:
$qualifying_array=array_filter(
$result,
function($val)use($arr1){ // pass in array to search
if(count(array_intersect($val,$arr1))==count($arr1)){ // total pairs found = total pairs sought
return $val;
}
}
);*/
echo 'Total sub-arrays which contain the search array($arr1): ',sizeof($qualifying_array),"<br>";
echo 'Keys of sub-arrays which contain the search array($arr1): ',implode(',',array_keys($qualifying_array)),"<br>";
echo 'Is search array($arr1) in the $result array?: ',(sizeof($qualifying_array)?"True":"False"),"<br>";
echo "<pre>";
print_r($qualifying_array);
echo "</pre>";
The output:
Total sub-arrays which contain the search array($arr1): 2
Keys of sub-arrays which contain the search array($arr1): 0,2
Is search array($arr1) in the $result array?: True
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
[10] => 11
[11] => 12
)
[2] => Array
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
[4] => 10
[5] => 12
)
)

how to make group of two array with given array in php?

i have one array and elements like:-
enter code here
$array = array('1', '2', '3', '4','5','6'); // n number of elements
echo "<pre>"; print_r($array); die;
when i print this array its give me this result
enter code here
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
i want output something like:-
enter code here
Array
(
[0] => Array
(
[0] => 1
[1] => 2
)
[1] => Array
(
[0] => 3
[1] => 4
)
[2] => Array
(
[0] => 5
[1] => 6
)
)
Can anyone help me how i can make two group of elements
Not:- array elements are dynamic it may be n number of elements
As you are requesting an example using foreach, you can use the modulus % mathematics operator to check every x.
$array = array( 1, 2, 3, 4, 5, 6 );
$tmp = array(); // temporarily hold values
$newarray = array(); // new array to hold final results
foreach ($array as $key=>$value) {
$tmp[] = $value; // add this value to temporary variable
if (($key + 1) % 2 == 0) {
$newarray[] = $tmp; // add temporary variable to new array
$tmp = array(); // reset temporary variable
}
}
// add remaining from odd number (if any)
if(count($tmp) > 0) {
$newarray[] = $tmp;
}

Categories