Related
I want to fetch input from view file and split that number into digits and replace each digit to a specific alphabet and then store it in database,
can anyone help me in this problem
$data = [
'product_id' => $productId,
'vendor_id' => $vendor_id,
'purchase_date' => $purchase_date,
'landing_price' => $landing_price,
'retail_price' => $retail_price,
'wholesale_price' => $wholesale_price,
'current_price' => $current_price,
'vendor_current_price' => $vendor_current_price,
'freight' => $freight
];
$numbers = str_split($wholesale_price);
$replaceNumbers = [
1 => 'S',
2 => 'H',
3 => 'O',
4 => 'N',
5 => 'E',
6 => 'L',
7 => 'A',
8 => 'P',
9 => 'U',
0 => 'R'
];
$replace = str_replace($numbers, $replaceNumbers, $numbers);
$JoinReplacedWord = join($replace);
var_dump($numbers, $replace, $JoinReplacedWord);
die;
but i am not getting the number replaced i am getting the array replaced to alphabet
result -
array(4) {
[0]=> string(1) "1"
[1]=> string(1) "4"
[2]=> string(1) "5"
[3]=> string(1) "0"
}
array(4) {
[0]=> string(1) "S"
[1]=> string(1) "H"
[2]=> string(1) "O"
[3]=> string(1) "N"
}
string(4) "SHON"
use array_replace instead str_replace
$wholesale_price = 98765;
$numbers = array_flip(str_split($wholesale_price));
$replaceNumbers = [
1 => 'S',
2 => 'H',
3 => 'O',
4 => 'N',
5 => 'E',
6 => 'L',
7 => 'A',
8 => 'P',
9 => 'U',
0 => 'R'
];
$replace = array_slice(array_replace($numbers, $replaceNumbers), 0, count($numbers));
$JoinReplacedWord = join($replace);
var_dump($JoinReplacedWord);
//you will see string(5) "UPALE"
die;
EDIT : bug fix for repeated digit example 88775
$wholesale_price = 88775;
$numbers = str_split($wholesale_price);
//remove array_flip, because array flip will cause array just use last index when number have repeated digit
$replaceNumbers = [
1 => 'S',
2 => 'H',
3 => 'O',
4 => 'N',
5 => 'E',
6 => 'L',
7 => 'A',
8 => 'P',
9 => 'U',
0 => 'R'
];
$string = "";
foreach($numbers as $val){
$string .= $replaceNumbers[$val];
}
var_dump($string);
//you will see string(5) "PPAAE"
die;
If you just define your $replaceNumbers array slightly different your code will work
$data = [
'product_id' => 1,
'vendor_id' => 2,
'purchase_date' => '2021-12-12',
'landing_price' => 123.45,
'retail_price' => 234.56,
'wholesale_price' => 12345678.90,
'current_price' => 456.78,
'vendor_current_price' => 567.89,
'freight' => 111.22
];
$replaceNumbers = ['R', 'S', 'H', 'O', 'N', 'E', 'L', 'A', 'P', 'U'];
$numbers = str_split($data['wholesale_price']);
$replace = str_replace($numbers, $replaceNumbers, $numbers);
$JoinReplacedWord = join($replace);
var_dump($numbers, $replace, $JoinReplacedWord);
RESULT
RSHONELAPU
I try to dig into this. According to your description, your code does exactly what you want it to do. It splits up $data['wholesale_price'] and has each character replaced as defined by $replaceNumbers. According to your output, your input number was '1450'.
Do you mean by "i am not getting the number replaced" that $data is not refreshed? Then simply add $data['wholesale_price'] = $JoinReplacedWord;.
I have an array like:-
([0] =>Array([amount] => 1, [address]=> 'a'),
[1] =>Array([amount] => 12, [address]=> 'b'),
[2] =>Array([amount] => -1, [address]=> 'a'),
[3] =>Array([amount] => 3, [address]=> 'a'))
How do I make an Loop so that at last I get amounts of a and only positive ones.
Let's say your array is this,
$array = array(
array('amount' => 3, 'address' => 'a'),
array('amount' => 26, 'address' => 'a'),
array('amount' => 345, 'address' => 'a'),
array('amount' => -3, 'address' => 'a'),
array('amount' => 22, 'address' => 'a'),
);
You can write a small for loop to achieve this,
$results = array();
foreach ($array as $k => $v){
if($v['amount'] > 0 && $v['address'] == 'a'){
$results[] = $v;
}
}
print_r($results);
This will give you elements where amount is greater than 0 and address is a. Is this what you looking for?
Could you be more precise with what you want ?
Assuming that your array is in an var called $_var
foreach($_var as $_array){
if($_array['amount'] > 0 && $_array['address']=='a'){ //if the amount is positiv and address = 'a'
$res[] = $_array; //Push the current item in your res array
}
}
$amount_of_a = count($res); //The number of a
print_r($res); //your result
I have a multi dimensional array, something like this:
$items = array(
'one' => array(
'a' => array(),
'b' => array(),
'c' => array()
),
'two' => array(
'd' => array(),
'e' => array(),
'f' => array()
),
'three' => array(
'g' => array(),
'h' => array(),
'i' => array()
)
);
So, I could add another array within the tree structure as:
$items['one']['c'][] = array( 'j' => array() );
But if I don't know that c is within one, how can I achieve this? I've looked at array_search but that just returns false. I think that is because what I'm looking for isn't at the top level of the array perhaps?
I know that c exists, but I don't know which sub-array it's in and how far down it goes. Is this possible?
If I understand you correctly, this function will do what you want:
<?php
$items = array(
'one' => array(
'a' => array(),
'b' => array(),
'c' => array()
),
'two' => array(
'd' => array(),
'e' => array(),
'f' => array()
),
'three' => array(
'g' => array(),
'h' => array(),
'i' => array()
)
);
function addToSub($items, $key, $addItem) {
foreach($items as &$item) {
if (in_array($key, array_keys($item))) {
$item[$key][] = $addItem;
}
}
return $items;
}
$items = addToSub($items, 'c', array( 'j' => array() ));
echo "<pre>";
var_dump($items);
echo "</pre>";
output:
array(3) {
["one"]=>
array(3) {
["a"]=>
array(0) {
}
["b"]=>
array(0) {
}
["c"]=>
array(1) {
[0]=>
array(1) {
["j"]=>
array(0) {
}
}
}
}
I think you are implementing a tree.
Your first thing to do is to find the node to append a child.
(In your example, the node is c and the child is j)
Implementing DFS search by recursion, I wrote following code.
(Make sure the node you're searching exists, or the function will return empty array)
<?php
$arr = [
'one' => [
'a' => [],
'b' => [],
'c' => [],
],
'two' => [
'd' => [],
'e' => [],
'f' => [],
],
'three' => [
'g' => [],
'h' => [],
'i' => [],
],
];
$arr = insertArr($arr, 'c', 'j');
print_r($arr);
function insertArr(array $arr, string $key, string $new): array {
// If key is found in $arr, append the child and return it.
if (array_key_exists($key, $arr)) {
$arr[$key][$new] = [];
return $arr;
}
// search the key in child node(next dimention)
foreach ($arr as $subArrKey => $subArr) {
// result will be empty if the key is not in child $subArr
$result = insertArr($subArr, $key, $new);
if (!empty($result)) {
// If the key is found in $subArr,
// replace $subArr with $result,
// which is the same as the $subArr but appended with child.
$arr[$subArrKey] = $result;
return $arr;
}
}
return [];
}
Now, you can append 'k' to either 'one', 'c' or 'j'.
To append 'k' to 'j', simply write:
$arr = insertArr($arr, 'j', 'k');
array_search will look for a value and in your example all your sub arrays are empty.
If I am not mistaken you could use array_map and for each subarray check if the key exists that you are looking for with array_key_exists:
$result = array_map(function($item) {
if (array_key_exists("c", $item)) {
$item["c"]["j"] = [];
}
return $item;
}, $items);
Demo
I have array like:-
$x = array(
'a' => array('aa' => array('aaa' => array(1, 2, 3))),
'b' => array('bb' => array('bbb' => array(1, 2, 3))),
);
Then, I want to modifying array to:-
$y = array(
1 => array('a', 'b'),
2 => array('aa', 'bb'),
3 => array('aaa', 'bbb'),
);
Please help me!
NB: if the last array 2,1,3 will be 2->a,b; 1->aa,bb; 3->aaa,bbb
You can try something like this:
$x = array(
'a' => array('aa' => array('aaa' => array(1, 2, 3))),
'b' => array('bb' => array('bbb' => array(1, 2, 3))),
);
$loop=true;
$item=array();
foreach ($x as $index => $value) {
if(!is_int($index)) $item[strlen($index)][]=$index;
while($loop){
foreach ($value as $sub_index => $sub_value) {
if (is_array($sub_value)) {
if(!is_int($sub_index)) $item[strlen($sub_index)][]=$sub_index;
$value=$sub_value;
}
else {
if(!is_int($sub_index))$item[strlen($sub_index)][]=$sub_index;
$loop=false;
}
}
}
$loop=true;
}
var_dump($item);
output
array(3) {
[1]=> array(2) { [0]=> string(1) "a" [1]=> string(1) "b" }
[2]=> array(2) { [0]=> string(2) "aa" [1]=> string(2) "bb" }
[3]=> array(2) { [0]=> string(3) "aaa" [1]=> string(3) "bbb" }
}
You could try the approach in the code below. And by the way, you could Quick-Test it Here.
<?php
$x = array(
'a' => array('aa' => array('aaa' => array(1, 2, 3))),
'b' => array('bb' => array('bbb' => array(1, 2, 3))),
);
$result = array();
$result[] = array_keys($x);
$tmp1 = [];
$tmp2 = [];
foreach($x as $k=>$arrData){
if(is_array($arrData)){
foreach($arrData as $k1=>$v1){
$tmp1[] = $k1;
if(is_array($v1)){
foreach($v1 as $k2=>$v2){
$tmp2[] = $k2;
}
}
}
}
}
$result[] = $tmp1;
$result[] = $tmp2;
var_dump($result);
//YIELDS:::
array (size=3)
0 =>
array (size=2)
0 => string 'a' (length=1)
1 => string 'b' (length=1)
1 =>
array (size=2)
0 => string 'aa' (length=2)
1 => string 'bb' (length=2)
2 =>
array (size=2)
0 => string 'aaa' (length=3)
1 => string 'bbb' (length=3)
Based on what you explained, I would suggest something like this:-
$x = array(
'a' => array('aa' => array('aaa' => array(1, 2, 3))),
'b' => array('bb' => array('bbb' => array(1, 2, 3))),
);
$y = array();
$l = array();
foreach ($x as $l[0] => $x2) {
foreach ($x2 as $l[1] => $x3) {
foreach ($x3 as $l[2] => $keys) {
for ($i = 0; $i < 3; $i++) {
if (isset($y[$keys[$i]])) {
$y[$keys[$i]][] = $l[$i];
} else {
$y[$keys[$i]] = array($l[$i]);
}
}
}
}
}
But please note that this code will fail if the depth changes or does not match the number of values that become keys...
I want to sort arrays by key in php, but the alphabet that I'm using is not the normal English alphabet -- it's a self-created alphabet. Is this possible?
My alphabet is:
$alphabet = "AjawbpfmnrhHxXsSqkgtTdD =";
The array is like this:
Array (
[=k_0] => Array(
[0] => DI.3,2 &dwA-nTr& #Hrw#
[1] => mA
[2] => =k
[3] => Sfj,t
[4] => =k
[5] => pXr
)
[aA_2] => Array(
[0] => DI.7,4 &dwA-nTr& #Hrw-smA-tA,wj#
[1] => snD
[2] => aA
[3] => Sfj,t
[4] => jt
[5] => jt,w
)
[sqA_1] => Array(
[0] => DI.6,18 &dwA-nTr& #nswt#
[1] => ra
[2] => sqA
[3] => Sfj,t
[4] => =s
[5] => r
)
);
So if I sort this array following my alphabet then the array with the key [=k_0] should be at the end.
You can use the usort() function and provide your own sorting logic.
See php.net for an example.
Edit: use uksort, not usort. See http://www.php.net/manual/en/function.uksort.php. Thanks #Darien!
A slightly modified example from php.net - the original code with an $alphabet mapping added:
function cmp($a, $b)
{
// custom sort order - just swapps 2 and 3.
$alphabet = array (1 => 1, 2 => 3, 3 => 2, 4 => 4, 5 => 5, 6=> 6);
if ($alphabet[$a] == $alphabet[$b]) {
return 0;
}
return ($alphabet[$a] < $alphabet[$b]) ? -1 : 1;
}
$a = array(3 => 'c' , 2 => 'b', 5 => 'e', 6 => 'f', 1=>'a');
uksort($a, "cmp");
foreach ($a as $key => $value) {
echo "$key: $value\n";
}
Given your $alphabet = "AjawbpfmnrhHxXsSqkgtTdD";, and assuming that A<j<a, etc, per your comment, transform each key in the alternative alphabet to a series in the known alphabet, e.g. use a mapping like:
your alphabet: AjawbpfmnrhHxXsSqkgtTdD
'real'alphabet: abcdefghijklmnopqrstuvw
So the key 'Ajaw' => 'abcd', and 'fmnr' => 'ghij', etc. This then turns your keys into something you can sort using conventional php functions. You'd need some way to handle characeters not present in your original alphabet though.
Something like that might work - you'd need two transform functions (from your alphabet to 'real' alphabet and vice versa), and then a comparator for e.g. uksort.
My two cents - thanks for clarifying the original question.
Fortunately, your custom alphabet does not have more characters than the list of single-byte latin letters, so translating is a very simple and readable process.
I recommend that you set up a translation array before you begin sorting, then translate/normalize the keys for the purpose of sorting.
Code: (Demo)
$array = [
'=k_0' => ['test1'],
'aA_2' => ['test2'],
'sqA_1' => ['test3'],
'=kj_0' => ['test4'],
'awA_2' => ['test5'],
'= D_1' => ['test6'],
'sq A_1' => ['test7'],
'sqA_2' => ['test8'],
];
$trans = ['AjawbpfmnrhHxXsSqkgtTdD =', 'abcdefghijklmnopqrstuvwxy'];
uksort(
$array,
function ($a, $b) use ($trans) {
return strtr($a, ...$trans) <=> strtr($b, ...$trans);
}
);
var_export($array);
Output:
array (
'aA_2' =>
array (
0 => 'test2',
),
'awA_2' =>
array (
0 => 'test5',
),
'sqA_1' =>
array (
0 => 'test3',
),
'sqA_2' =>
array (
0 => 'test8',
),
'sq A_1' =>
array (
0 => 'test7',
),
'=k_0' =>
array (
0 => 'test1',
),
'=kj_0' =>
array (
0 => 'test4',
),
'= D_1' =>
array (
0 => 'test6',
),
)
From PHP7.4, the syntax can be reduced using arrow function syntax.
uksort(
$array,
fn($a, $b) => strtr($a, ...$trans) <=> strtr($b, ...$trans)
);
After feedback from #mickmackusa I have updated my example to work with uksrot and answer the question fully
$order = str_split("AjawbpfmnrhHxXsSqkgtTdD");
uksort($arr, function ($a, $b) use ($order) {
$posA = array_search($a, $order);
$posB = array_search($b, $order);
return $posA - $posB;
});
http://sandbox.onlinephpfunctions.com/code/9b6f39b30dcc932517bbe82608dd8a0c8d35b3da
-- original response with usort--
You can use usort() with a custom order array like so
$arr = array("w","b","m","n","x","x","z","T","T","A","A");
$order = array("A","j","a","w","b","p","f","m","n","r","h","H","x","X","s","S","q","k","g","t","T","d","D"," ","=");
usort($arr, function ($a, $b) use ($order) {
$posA = array_search($a, $order);
$posB = array_search($b, $order);
return $posA - $posB;
});
(you could probably just explode the $order string so it's nicer)
I actually just came across this answer which explains it better, and handles if a value is not inside the order array.
And a working example http://sandbox.onlinephpfunctions.com/code/3934aafe93377ec18549d326d6551608436242a7
<?php
$arr = [8,10,12,18,20,7,4,6,2,20,0]; //take array
$a= sortasc($arr); // call function
function sortasc($arr){
for($i=0;$i<=count($arr);$i++){
for($j=1;$j<=count($arr)-1;$j++){
if($arr[$j-1]>$arr[$j]){
$temp = $arr[$j];
$arr[$j]= $arr[$j-1];
$arr[$j-1] = $temp;
}
}
}
return $arr;
}
?>
See this code:
<?php
$arr = array('wr' => 1, 'wrS' => 6, 'wr,w' => 3, 'wr.w' => 4, 'wr-qA' => 2, 'wrs' => 5);
function compare_by_alphabet(array $alphabet, $str1, $str2)
{
$l1 = strlen($str1);
$l2 = strlen($str2);
$c = min($l1, $l2);
for ($i = 0; $i < $c; $i++)
{
$s1 = $str1[$i];
$s2 = $str2[$i];
if ($s1===$s2) continue;
$i1 = array_search($s1, $alphabet);
if ($i1===false) continue;
$i2 = array_search($s2, $alphabet);
if ($i2===false) continue;
if ($i2===$i1) continue;
if ($i1 < $i2) return -1;
else return 1;
}
if ($l1 < $l2) return -1;
elseif ($l1 > $l2) return 1;
return 0;
}
function compare_keys_by_alphabet($a, $b)
{
static $alphabet = array('-', ',', '.', 'A', 'j', 'a', 'w', 'b', 'p', 'f', 'm', 'n', 'r', 'h', 'H', 'x', 'X', 's', 'S', 'q', 'โโk', 'g', 't', 'T', 'd', 'D', '=', '/', '(', ')', '[', ']', '<', '>', '{', '}', '\'', '*', '#', 'I', 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, '&', '#');
return compare_by_alphabet($alphabet, $a, $b);
}
uksort($arr, 'compare_keys_by_alphabet');
print_r($arr);
Result:
Array
(
[wr] => 1
[wr-qA] => 2
[wr,w] => 3
[wr.w] => 4
[wrs] => 5
[wrS] => 6
)