php multidimensional array: how to remove duplicate entries - php

in fear of duplicating content, i have looked through so many similar SO questions, but i think i need a bit more than code, to tell me how solve my problem- would be lovely with some explaination too.
How do i turn $list:
array(4) {
[0]=>
array(2) {
["title"]=>
string(8) "Zambezia"
["id"]=>
int(31)
}
[1]=>
array(2) {
["title"]=>
string(6) "Zarafa"
["id"]=>
int(34)
}
[2]=>
array(2) {
["title"]=>
string(8) "Zambezia"
["id"]=>
int(31)
}
[3]=>
array(2) {
["title"]=>
string(8) "Zambezia"
["id"]=>
int(31)
}
}
Into $list:
array(2) {
[0]=>
array(2) {
["title"]=>
string(8) "Zambezia"
["id"]=>
int(31)
}
[1]=>
array(2) {
["title"]=>
string(6) "Zarafa"
["id"]=>
int(34)
}
}
By removing duplicate entries?

Use array_unique() with SORT_REGULAR flag.
$new_array = array_unique($array, SORT_REGULAR);
Output should be:
Array
(
[0] => Array
(
[title] => Zambezia
[id] => 31
)
[1] => Array
(
[title] => Zarafa
[id] => 34
)
)
Demo.

Related

Why is there an undefined index on a Boolean array?

For some reasons, when I try to do an if for $value['is_set'] == false, I get undefined index error, however, if I do an isset($value['is_set']) I get 1
I did a print_r and got the ff:
Array ( [is_set] => [product] => Array ( [product_ID] => 1 [product_name] => Insulated Terminal Lugs 1.25 - 3Y [product_code] => [unit_ID] => 80 [unit_name] => pc(s) [price] => 50 [qty] => 1 [discount] => 0 [subtotal] => 50 [amount] => 50 ) [set] => Array ( [set_ID] => [set_items] => Array ( [0] => Array ( [amount] => 0 ) ) [amount] => 0 ) [selectedProduct] => Array ( [ID] => 1 [product_name] => Insulated Terminal Lugs 1.25 - 3Y [product_code] => [price] => 50 ) [selectedUnit] => Array ( [ID] => 80 [option_key] => pc(s) ) [amount] => 50 )
why is this happening?
here is my code:
public function create($model, $value, $datetime, $transaction_type, $notes) {
if (($model->general_status == Sales::GEN_STATUS_OPEN || $model->general_status == Sales::GEN_STATUS_CLOSED) && ($model->delivery_status == Sales::DELIVERY_STATUS_DELIVERED)) {
$pth = new ProductTransactionHistory();
//var_dump($value); exit();
if ($value['is_set'] == false) {
$pth->generateSales($transaction_type, $datetime, '(add)', $model, $value, Yii::$app->user->id, $notes);
$pth->stock_in_out = ProductTransactionHistory::STOCK_OUT;
//$pth->save();
$this->saveDebug($pth);
}
}
this function is called by the following code:
$so = Json::decode($request['purchase-orders']);
foreach ($so['orders'] as $key => $value) {
$order->create($model, $value, $datetime);
}
the full var_dump of $so is
array(8) { ["orders"]=> array(2) { [0]=> array(6) { ["is_set"]=> bool(false) ["product"]=> array(10) { ["product_ID"]=> string(1) "1" ["product_name"]=> string(33) "Insulated Terminal Lugs 1.25 - 3Y" ["product_code"]=> string(0) "" ["unit_ID"]=> string(2) "80" ["unit_name"]=> string(5) "pc(s)" ["price"]=> string(2) "50" ["qty"]=> int(1) ["discount"]=> int(0) ["subtotal"]=> int(50) ["amount"]=> int(50) } ["set"]=> array(3) { ["set_ID"]=> bool(false) ["set_items"]=> array(1) { [0]=> array(1) { ["amount"]=> int(0) } } ["amount"]=> int(0) } ["selectedProduct"]=> array(4) { ["ID"]=> string(1) "1" ["product_name"]=> string(33) "Insulated Terminal Lugs 1.25 - 3Y" ["product_code"]=> string(0) "" ["price"]=> string(2) "50" } ["selectedUnit"]=> array(2) { ["ID"]=> string(2) "80" ["option_key"]=> string(5) "pc(s)" } ["amount"]=> int(50) } [1]=> array(5) { ["is_set"]=> bool(true) ["product"]=> array(3) { ["unit_ID"]=> string(0) "" ["unit_name"]=> string(0) "" ["amount"]=> int(0) } ["set"]=> array(3) { ["set_ID"]=> string(1) "1" ["set_items"]=> array(2) { [0]=> array(10) { ["product_ID"]=> int(4) ["product_name"]=> string(33) "Power Miniature Solder Relay 220v" ["product_code"]=> string(5) "LY4NJ" ["unit_ID"]=> int(80) ["unit_name"]=> string(5) "pc(s)" ["qty"]=> int(1) ["price"]=> int(200) ["discount"]=> int(0) ["subtotal"]=> int(200) ["amount"]=> int(200) } [1]=> array(10) { ["product_ID"]=> int(5) ["product_name"]=> string(26) "Relay Socket 14A for LY4NJ" ["product_code"]=> string(6) "PYF14A" ["unit_ID"]=> int(80) ["unit_name"]=> string(5) "pc(s)" ["qty"]=> int(1) ["price"]=> int(20) ["discount"]=> int(0) ["subtotal"]=> int(20) ["amount"]=> int(20) } } ["amount"]=> int(220) } ["selectedSet"]=> array(3) { ["ID"]=> string(1) "1" ["set_name"]=> string(20) "LY4NJ 220v w/ Socket" ["price"]=> string(3) "220" } ["amount"]=> int(220) } } ["has_downpayment"]=> bool(false) ["payment_type"]=> string(4) "cash" ["grandTotal"]=> int(270) ["generalStatus"]=> string(6) "closed" ["statusText"]=> string(6) "Cancel" ["cssStatus"]=> string(14) "btn btn-danger" ["showPayment"]=> bool(false) }
the full error is:
PHP Notice – yii\base\ErrorException
Undefined index: is_set
also this is related to this issue:
Why does accessing array index on boolean value does not raise any kind of error?
but I don't know how to get pass this without using array...
Initially I tried empty($value['is_set']) as an alternative, but it didn't work and I freaked out. I reconsidered that option again and found that it works! I don't know why it didn't work earlier. Thanks for all your support!

Regex date formatting for templates not working

I'm trying to replace variables like {{{month}}} in a template to the current month and {{{month+1}}} to current month + 1.
That's not the hardest part of my code, except that the regex I wrote doesn't yield expected results.
$string = '{{{year}}}{{{month+1}}}';
preg_match_all('/{{{(?:([yY])ear|([mM])onth|([dD])ay)(?:(?<operation>[-|+])(?<amount>[1-9]+))?}}}/m', $string, $matches);
var_dump($matches);
Why do I have so much empty array entries?
I was expecting
[0] => array('{{{year}}}', '{{{month+1}}}')
[1] => array('y', 'm')
[2] => array('', '+')
[3] => array('', '1')
What am I doing wrong?
The respond of the above code is:
array(8) {
[0]=>
array(2) {
[0]=>
string(10) "{{{year}}}"
[1]=>
string(13) "{{{month+1}}}"
}
[1]=>
array(2) {
[0]=>
string(1) "y"
[1]=>
string(0) ""
}
[2]=>
array(2) {
[0]=>
string(0) ""
[1]=>
string(1) "m"
}
[3]=>
array(2) {
[0]=>
string(0) ""
[1]=>
string(0) ""
}
["operation"]=>
array(2) {
[0]=>
string(0) ""
[1]=>
string(1) "+"
}
[4]=>
array(2) {
[0]=>
string(0) ""
[1]=>
string(1) "+"
}
["amount"]=>
array(2) {
[0]=>
string(0) ""
[1]=>
string(1) "1"
}
[5]=>
array(2) {
[0]=>
string(0) ""
[1]=>
string(1) "1"
}
}
You may use a "generic" character class to match the first letters of month, year and day, and then use an alternation with positive look-behinds to make sure we match what we need.
preg_match_all('/{{{([yYmMdD])(?:(?<=[Yy])ear|(?<=[Mm])onth|(?<=[Dd])ay)(?:([-‌​+])([1-9]+))?}}}/m', $string, $matches);
See IDEONE demo
And this is the print_r view:
Array
(
[0] => Array
(
[0] => {{{year}}}
[1] => {{{month+1}}}
)
[1] => Array
(
[0] => y
[1] => m
)
[2] => Array
(
[0] =>
[1] => +
)
[3] => Array
(
[0] =>
[1] => 1
)
)

Create array from array values

I have an array like this :
$lessonOptions=array();
$lessonOptions[0]=array("Physics","6.00","2015-01-01","-","4");
$lessonOptions[1]=array("Physics","16.00","2015-01-01","-","2");
$lessonOptions[2]=array("Maths","10.00","2015-07-01","-","10");
$lessonOptions[3]=array("Maths","20.00","2015-07-01","-","10");
I want to create an output with new array called optionarray which contains:
**
physics 6.00 2015-01-04 -
physics 16.00 2015-01-01 -
maths 10.00 2015-07-01 -
maths 20.00 2015-07-07 -
My problem is that I can see every line of maths but only one line of physics is missing .
How can I display all line ?
My actual code is :
$lessonGroup=$lessonOptions[0][0];
$display=FALSE;
$state=0;
$nbLessons=count($lessonsOptions);
for ($i = 0; $i<$nbLessons; $i++)
{
if ($i+1!=$nbLessons) $lessonGroupSuivant=$lessonOptions[$i+1][0];
else $display=TRUE;
switch ($state)
{
case 0 :
$infoLesson[$state]=$lessonOptions[$i];
default :
{
if ($lessonGroup==$lessonGroupSuivant)
{
$infoLesson[$state]=$lessonOptions[$i];
$state=$state+1;
}
else
{
$display=TRUE;
$lessonGroup=$lessonGroupSuivant;
$state=0;
}
}
}
if ($display==TRUE)
{
//var_dump($infoLesson);
$display=FALSE;
}
}
My actual array (wrong)
As you can see, the size of my array is 1 , I need to have 2 because I have two field for the lesson physics.
array(1) { [0]=> array(5) { [0]=> string(31) "physics" [1]=> string(10) "6.00" [2]=> string(10) "2015-01-01" [3]=> string(1) "-" [4]=> float(42) } }
array(2) { [0]=> array(5) { [0]=> string(15) "Maths" [1]=> string(11) "10.00" [2]=> string(10) "2015-07-01" [3]=> string(1) "-" [4]=> float(10) } [1]=> array(5) { [0]=> string(15) "Maths" [1]=> string(11) "10.00" [2]=> string(10) "2015-07-12" [3]=> string(1) "-" [4]=> float(10) } }
Okay i think i found what you need:
<?php
$lessonOptions=array();
$lessonOptions[0]=array("Physics","6.00","2015-01-01","-","4");
$lessonOptions[1]=array("Physics","16.00","2015-01-01","-","2");
$lessonOptions[2]=array("Maths","10.00","2015-07-01","-","10");
$lessonOptions[3]=array("Maths","20.00","2015-07-01","-","10");
$optionarray = array();
$lastLessonKey = '';
$i = 0;
foreach ($lessonOptions as $key => $data) {
if (empty($lastLessonKey)) {
$lastLessonKey = $data[0];
} else if ($lastLessonKey !== $data[0]) {
$i++;
$lastLessonKey = $data[0];
}
$optionarray[$i][] = $data;
}
var_dump($optionarray);
Output:
array(2) { [0]=> array(2) { [0]=> array(5) { [0]=> string(7) "Physics" [1]=> string(4) "6.00" [2]=> string(10) "2015-01-01" [3]=> string(1) "-" [4]=> string(1) "4" } [1]=> array(5) { [0]=> string(7) "Physics" [1]=> string(5) "16.00" [2]=> string(10) "2015-01-01" [3]=> string(1) "-" [4]=> string(1) "2" } } [1]=> array(2) { [0]=> array(5) { [0]=> string(5) "Maths" [1]=> string(5) "10.00" [2]=> string(10) "2015-07-01" [3]=> string(1) "-" [4]=> string(2) "10" } [1]=> array(5) { [0]=> string(5) "Maths" [1]=> string(5) "20.00" [2]=> string(10) "2015-07-01" [3]=> string(1) "-" [4]=> string(2) "10" } } }
So, you are willing to group arrays by some value
$infoLesson = array();
foreach ($lessonOptions as $v) {
$infoLesson[$v[0]][] = $v;
}
You can then retrieve arrays by key.
For example printing $infoLesson['Maths'] will get you
Array
(
[0] => Array
(
[0] => Maths
[1] => 10.00
[2] => 2015-07-01
[3] => -
[4] => 10
)
[1] => Array
(
[0] => Maths
[1] => 20.00
[2] => 2015-07-01
[3] => -
[4] => 10
)
)
And $infoLesson['Physics']
Array
(
[0] => Array
(
[0] => Physics
[1] => 6.00
[2] => 2015-01-01
[3] => -
[4] => 4
)
[1] => Array
(
[0] => Physics
[1] => 16.00
[2] => 2015-01-01
[3] => -
[4] => 2
)
)

How to sort the array by the value of given key in my case?

I need to sort the array by the value of the given key 0 in this case.
So here is my array:
array(11) {
[0]=> array(3) {
[0]=> string(3) "5"
[1]=> string(1) "3"
[2]=> string(2) "21"
}
[1]=> array(3) {
[0]=> string(3) "0.5"
[1]=> string(1) "3"
[2]=> string(3) "may"
}
[2]=> array(3) {
[0]=> string(3) "2.2"
[1]=> string(1) "3"
[2]=> string(16) "sport"
}
}
Result must be sorted by the value of key 0:
array(11) {
[0]=> array(3) {
[0]=> string(3) "0.5"
[1]=> string(1) "3"
[2]=> string(2) "may"
}
[1]=> array(3) {
[0]=> string(3) "2.2"
[1]=> string(1) "3"
[2]=> string(3) "sport"
}
[2]=> array(3) {
[0]=> string(3) "5"
[1]=> string(1) "3"
[2]=> string(16) "21"
}
}
I attempted it with this code:
function sort_by_second($i,$j){return $i[0]-$j[0];};
usort($mas,'sort_by_second');
I don't understand why it doesn't work.
Try below code:
$array = array(
array("5","3","21"),
array("0.5","3","may"),
array("2.2","3","sport"),
);
//print_r($array);
function subval_sort($a,$subkey) {
foreach($a as $k=>$v) {
$b[$k] = strtolower($v[$subkey]);
}
asort($b);
foreach($b as $key=>$val) {
$c[] = $a[$key];
}
return $c;
}
$result = subval_sort($array, 0);
print_r($result);
Result:
Array
(
[0] => Array
(
[0] => 0.5
[1] => 3
[2] => may
)
[1] => Array
(
[0] => 2.2
[1] => 3
[2] => sport
)
[2] => Array
(
[0] => 5
[1] => 3
[2] => 21
)
)
Demo:
http://3v4l.org/q4ZtL#v430
PHP >= 5.5.0:
array_multisort(array_column($array, 0), SORT_ASC, $array);

Having trouble with a recursion algo

Okay here is my recursion algo:
public function getCategoryTree($tree,$return = array()) {
foreach ($tree->children as $child) {
if (count($child->children) > 0 )
$return[$tree->name] = $this->getCategoryTree($child, $return);
else
$return[] = $child->name;
}
return $return;
}
Here is a snippet of the data structure I'm trying to traverse
Object(stdClass)#290 (6) {
["category_id"]=>
int(1)
["parent_id"]=>
int(0)
["name"]=>
string(4) "Root"
["position"]=>
int(0)
["level"]=>
int(0)
["children"]=>
array(2) {
[0]=>
object(stdClass)#571 (7) {
["category_id"]=>
int(2)
["parent_id"]=>
int(1)
["name"]=>
string(18) "Root MySite.com"
["is_active"]=>
int(0)
["position"]=>
int(0)
["level"]=>
int(1)
["children"]=>
array(11) {
[0]=>
object(stdClass)#570 (7) {
["category_id"]=>
int(15)
["parent_id"]=>
int(2)
["name"]=>
string(9) "Widgets"
["is_active"]=>
int(1)
["position"]=>
int(68)
["level"]=>
int(2)
["children"]=>
array(19) {
[0]=>
object(stdClass)#566 (7) {
["category_id"]=>
int(24)
["parent_id"]=>
int(15)
["name"]=>
string(16) "Blue widgets"
["is_active"]=>
int(1)
["position"]=>
int(68)
["level"]=>
int(3)
["children"]=>
array(0) {
}
}
<snip....>
I'm trying to get a php data structure like such
categories = array( "Root" =>
array("Root MySite.com" =>
array( "Widgets" =>
// final element is NOT an array
array ("Blue Widgets", "Purple Widgets" ...)
)
)
)
I can't quite seem to get the data structure i'm looking for using my recursive algo. Any help
would be great.
Eventually I'll need to parse it again on the frontend and display it, but another problem for another day...
Have a look at this phpFiddle for a full working example. The only error I found was the $this->getCategoryTree which gave me an Fatal Error Using $this when not in object context. So are you sure the function is within the correct scope?
Updated
I hope this one works. :)
function traverse($root, $return = array()) {
$return[$root->name] = array();
foreach ($root->children as $child) {
if (count($child->children) > 0) {
traverse($child, &$return[$root->name]);
}else {
array_push(&$return[$root->name], $child->name);
}
}
return $return;
}
The output from this is:
Array ( [Root] =>
Array (
[Root MySite.com] =>
Array (
[Widgets] => Array ( [0] => Blue Widget [1] => Purple Widget)
[Gizmos] => Array ( [0] => Blue Gizmos [1] => Purple Gizmos)
)
[FooBar.com] =>
Array (
[Widgets] => Array ( [0] => Blue Widget [1] => Purple Widget)
[Gizmos] => Array ( [0] => Blue Gizmos [1] => Purple Gizmos)
)
)
)
Again, full working example

Categories