Creating Array Key Name with Dynamic Array - php

I am trying to get the example below to have key names for each dimension so it would look more like this:
Array
(
[Mobile] => Array
(
[0] => Array
(
[product_id] => 007
[product_name] => Blackberry R-900 Mobile
[product_price] => £450
[product_status] => 1
[product_category] => Mobile
)
Instead of the example below,
I have included the class that I am using to create the array into a categorized array and the usage of it.
The function appendNode in array2arraytree is where the algorithm actually creates the new array for each category.
Thanks for any help.
Example:
Array
(
[0] => Array
(
[0] => Array
(
[product_id] => 007
[product_name] => Blackberry R-900 Mobile
[product_price] => £450
[product_status] => 1
[product_category] => Mobile
)
[1] => Array
(
[product_id] => 001
[product_name] => Wespro Multi-SIM & Touch-screen Mobile
[product_price] => £150
[product_status] => 1
[product_category] => Mobile
)
[2] => Array
(
[product_id] => 004
[product_name] => Sigmatel MP4/MP3 + Camera Mobile
[product_price] => £150
[product_status] => 1
[product_category] => Mobile
)
)
[1] => Array
(
[0] => Array
(
[product_id] => 033
[product_name] => 8 GB Pendrive
[product_price] => £14.99
[product_status] => 0
[product_category] => Computers
)
[1] => Array
(
[product_id] => 334
[product_name] => 250 GB Portable Hard Drive
[product_price] => £79.99
[product_status] => 1
[product_category] => Computers
)
)
[2] => Array
(
[0] => Array
(
[product_id] => 033
[product_name] => The White Tiger – Aravind Adiga
[product_price] => £29.99
[product_status] => 1
[product_category] => Books
)
[1] => Array
(
[product_id] => 4501
[product_name] => The Final Reckoning - Sam Bourne
[product_price] => £19.99
[product_status] => 0
[product_category] => Books
)
[2] => Array
(
[product_id] => 034
[product_name] => The Final Reckoning - Sam Bourne
[product_price] => £15.79
[product_status] => 0
[product_category] => Books
)
)
)
Usage:
<?php
require_once("array2arraytree.php");
$arrProducts=array(
array(
"product_id" => "007",
"product_name" => "Blackberry R-900 Mobile",
"product_price" => "£450",
"product_status" =>"1",
"product_category" =>"Mobile"
),
array(
"product_id" => "033",
"product_name" => "8 GB Pendrive",
"product_price" => "£14.99",
"product_status" => "0",
"product_category" => "Computers"
),
array(
"product_id" => "033",
"product_name" => "The White Tiger – Aravind Adiga",
"product_price" => "£29.99",
"product_status" => "1",
"product_category" => "Books"
),
array(
"product_id" => "4501",
"product_name" => "The Final Reckoning - Sam Bourne",
"product_price" => "£19.99",
"product_status" => "0",
"product_category" => "Books"
),
array(
"product_id" => "001",
"product_name" => "Wespro Multi-SIM & Touch-screen Mobile",
"product_price" => "£150",
"product_status" => "1",
"product_category" => "Mobile"
),
array(
"product_id" => "004",
"product_name" => "Sigmatel MP4/MP3 + Camera Mobile",
"product_price" => "£150",
"product_status" => "1",
"product_category" => "Mobile"
),
array(
"product_id" => "034",
"product_name" => "The Final Reckoning - Sam Bourne",
"product_price" => "£15.79",
"product_status" => "0",
"product_category" => "Books"
),
array(
"product_id" => "334",
"product_name" => "250 GB Portable Hard Drive",
"product_price" => "£79.99",
"product_status" => "1",
"product_category" => "Computers"
)
);
$objTree=new Array2ArrayTree($arrProducts,"product_category");
$arrTree=$objTree->makeTree();
print("<pre>");
print_r($arrTree);
print("</pre>");
?>
Class Array2ArrayTree:
class Array2ArrayTree
{
public $arrOriginal = array();
public $arrDummy = array();
public $strKey = "";
public function __construct($arrData, $arrKey)
{
$this->arrOriginal = $arrData;
$this->strKey = $arrKey;
$this->arrDummy = array();
}
public function makeTree()
{
for ($i = 0; $i <= sizeof($this->arrOriginal) - 1; $i++) {
$keyPosition = $this->searchKey($this->arrOriginal[$i][$this->strKey]);
if ($keyPosition == -1) {
$this->addNode($this->arrOriginal[$i]);
} else {
$this->appendNode($this->arrOriginal[$i], $keyPosition);
}
}
return $this->arrDummy;
}
function searchKey($strCurrentValue)
{
for ($i = 0; $i <= sizeof($this->arrDummy) - 1; $i++) {
if ($this->arrDummy[$i][0][$this->strKey] == $strCurrentValue) {
return $i;
}
}
return - 1;
}
function addNode($arrNode)
{
$this->arrDummy[sizeof($this->arrDummy)][0] = $arrNode;
}
function appendNode($arrNode, $keyPosition)
{
array_push($this->arrDummy[$keyPosition], $arrNode);
}
}
?>

Should be even simpler:
public function makeTree()
{
foreach($this->arrOriginal as $value) {
$this->arrDummy[$value[$this->strKey]][] = $value;
}
return $this->arrDummy;
}

I think this would work - map the array to get the keys you want, then use array_filter to get only the items in that category:
//get the keys you want:
$keys = array_unique(array_map(function($item) { return $item['product_category']; }, $array));
$return = [];
foreach($keys as $key) {
//filter the array to the one's in the current category, and reindex them to 0:
$return[$key] = array_values(array_filter($array, function($item) use ($key) {
return $item['product_category'] == $key;
}));
}

Related

Forming final array with multiple array in PHP [duplicate]

This question already has answers here:
How to find array / dictionary value using key?
(2 answers)
Closed 3 years ago.
I need to form the final array, its not displaying how i am expecting, here is the code i used.
I need to print the final array in the expected format, I have attached the output how i am looking for in the below section,
<?php
$order_id = 12345;
$array1 = array(
"firstName" => "Test Fname",
"lastName" => "Test Lname",
"address1" => "Test Address",
"city" => "Test City",
"country" => "IND",
"email" => "test#blank.in"
);
$array2 = array(
"firstName" => "Test Fname",
"lastName" => "Test Lname",
"address1" => "Test Address",
"city" => "Test City",
"country" => "IND",
"email" => "test#blank.in"
);
$result = array("user_id" =>"9999","item_id" =>"cloth","price" =>"500","qty" =>"100");
$itemDetails = array();
foreach($result as $res){
$itemDetails[] =
array(
"User" => array(
"uservalue" => $res['user_id'],
"imageId" => $res['item_id']
),
"price" => $res['price'],
"qty" => $res['qty']
);
}
$final_array = array(
"id" => $order_id,
"billing" => $array1,
"shipping" => $array2,
"item" => $itemDetails
);
echo '<pre>';
print_r($final_array);die;
?>
Output of current Code
Array
(
[id] => 12345
[billing] => Array
(
[firstName] => Test Fname
[lastName] => Test Lname
[address1] => Test Address
[city] => Test City
[country] => IND
[email] => test#blank.in
)
[shipping] => Array
(
[firstName] => Test Fname
[lastName] => Test Lname
[address1] => Test Address
[city] => Test City
[country] => IND
[email] => test#blank.in
)
[item] => Array
(
[0] => Array
(
[User] => Array
(
[uservalue] => 9999
[imageId] => cloth
)
[price] => 500
[qty] => 100
)
[1] => Array
(
[User] => Array
(
[uservalue] => 9999
[imageId] => cloth
)
[price] => 500
[qty] => 100
)
[2] => Array
(
[User] => Array
(
[uservalue] => 9999
[imageId] => cloth
)
[price] => 500
[qty] => 100
)
)
)
Expected Result should be like below
array
(
"id" => 12345
"billing" => array
(
[firstName] => Test Fname,
[lastName] => Test Lname,
[address1] => Test Address,
[city] => Test City,
[country] => IND,
[email] => test#blank.in
)
"shipping" => array
(
[firstName] => Test Fname,
[lastName] => Test Lname,
[address1] => Test Address,
[city] => Test City,
[country] => IND,
[email] => test#blank.in
)
"item" => array
(
array
(
"User" => Array
(
"uservalue" => 9999,
"imageId" => cloth
)
[price] => 500,
[qty] => 100
)
)
)
I am expecting output like above, can we display the final array in that format, can anyone look into it and update me your thoughts. Thanks!!
if you allow only single item in itemdetails
$itemDetails[] =
[
"User" => [
"uservalue" => $result['user_id'],
"imageId" => $result['item_id'],
],
"price" => $result['price'],
"qty" => $result['qty'],
];
Single item demo
if itemdetails allow multiple items
$result = [
["user_id" =>"9999","item_id" =>"cloth","price" =>"500","qty" =>"100"],
["user_id" =>"9999","item_id" =>"cloth","price" =>"400","qty" =>"200"]
];
$itemDetails = array();
foreach($result as $res){
$itemDetails[] =
array(
"User" => array(
"uservalue" => $res['user_id'],
"imageId" => $res['item_id']
),
"price" => $res['price'],
"qty" => $res['qty']
);
}
Multiple items demo
If $result has multiple values, this should work.
$result = array(array("user_id" =>"9999","item_id" =>"cloth","price" =>"500","qty" =>"100"),array("user_id" =>"500","item_id" =>"cloth123","price" =>"511","qty" =>"80"));
$itemDetails = array();
foreach($result as $res){
$itemDetails[] =
array(
"User" => array(
"uservalue" => $res['user_id'],
"imageId" => $res['item_id']
),
"price" => $res['price'],
"qty" => $res['qty']
);
}
$final_array = array(
// "id" => $order_id,
// "billing" => $array1,
// "shipping" => $array2,
"item" => $itemDetails
);
echo '<pre>';
print_r($final_array);
Output
Array
(
[item] => Array
(
[0] => Array
(
[User] => Array
(
[uservalue] => 9999
[imageId] => cloth
)
[price] => 500
[qty] => 100
)
[1] => Array
(
[User] => Array
(
[uservalue] => 500
[imageId] => cloth123
)
[price] => 511
[qty] => 80
)
)
)

Group and Calculate Values in Array

I have an array like the following:
Array
(
[0] => Array
(
[0] => Array
(
[Product_Name] => Apple Pie - 8"
[Product_Qty] => 1
[Product_Cat] => Pies
)
[1] => Array
(
[Product_Name] => Pecan Pie - 8"
[Product_Qty] => 1
[Product_Cat] => Pies
)
)
[1] => Array
(
[0] => Array
(
[Product_Name] => Apple Pie - 8"
[Product_Qty] => 1
[Product_Cat] => Pies
)
)
[2] => Array
(
[0] => Array
(
[Product_Name] => Strawberry Pie - 8"
[Product_Qty] => 1
[Product_Cat] => Pies
)
[1] => Array
(
[Product_Name] => Pecan Pie - 8"
[Product_Qty] => 1
[Product_Cat] => Pies
)
)
[3] => Array
(
[0] => Array
(
[Product_Name] => Lemon Pie - 8"
[Product_Qty] => 1
[Product_Cat] => Pies
)
[1] => Array
(
[Product_Name] => Pecan Pie - 8"
[Product_Qty] => 1
[Product_Cat] => Pies
)
)
)
I'm trying to group by same Product_Name and also add up the Product_Qty in each. Any help is greatly appreciated.
You can create a double loop and sum all value of every different product under a different array key as below:
$myArr = [
0 => [
0 => [
"Product_Name" => "Apple Pie - 8",
"Product_Qty" => 1,
"Product_Cat" => "Pies"
],
1 => [
"Product_Name" => "Apple Pie - 8",
"Product_Qty" => 1,
"Product_Cat" => "Pies"
]
],
1 => [
0 => [
"Product_Name" => "Pecan Pie - 8",
"Product_Qty" => 1,
"Product_Cat" => "Pies"
]
],
2 => [
0 => [
"Product_Name" => "Strawberry Pie - 8",
"Product_Qty" => 1,
"Product_Cat" => "Pies"
],
1 => [
"Product_Name" => "Pecan Pie - 8",
"Product_Qty" => 1,
"Product_Cat" => "Pies"
]
],
3 => [
0 => [
"Product_Name" => "Lemon Pie - 8",
"Product_Qty" => 1,
"Product_Cat" => "Pies"
],
1 => [
"Product_Name" => "Pecan Pie - 8",
"Product_Qty" => 1,
"Product_Cat" => "Pies"
]
]
];
$total = [];
foreach($myArr as $group){
foreach($group as $item){
$total[$item["Product_Name"]] = isset($total[$item["Product_Name"]]) ? $total[$item["Product_Name"]] + $item["Product_Qty"] : $item["Product_Qty"];
}
}
var_dump($total);
It will provide that total:
array(4) {
["Apple Pie - 8"]=>
int(2)
["Pecan Pie - 8"]=>
int(3)
["Strawberry Pie - 8"]=>
int(1)
["Lemon Pie - 8"]=>
int(1)
}
If you want to get all data as in array now then you can run below code.
$finalArray = array();
$product_name_arr = array();
foreach ($array as $key => $value) {
foreach ($value as $sub_key => $sub_value) {
if(in_array($sub_value['Product_Name'], $product_name_arr)){
foreach ($finalArray as $fa_key => $fa_value) {
if($fa_value['Product_Name'] == $sub_value['Product_Name']){
$finalArray[$fa_key]['Product_Qty'] = $finalArray[$fa_key]['Product_Qty'] + $sub_value['Product_Qty'];
}
}
} else {
$product_name_arr[] = $sub_value['Product_Name'];
$finalArray[] = $sub_value;
}
}
}

Merging two multi-dimensional arrays using key and adding values

I want to merge two array's using key(product_id) and adding that values(usage).
Array 1
Array
(
[0] => Array
(
[name] => Reschedule A Service
[usage] => 1
[product_id] => 8
)
[1] => Array
(
[name] => Adding An Image
[usage] => 1
[product_id] => 5
)
[2] => Array
(
[name] => Each Calendar Event
[usage] => 1
[product_id] => 14
)
)
Array 2
Array
(
[0] => Array
(
[name] => Adding An Image
[usage] => 1
[product_id] => 5
)
[1] => Array
(
[name] => Schedule A Service
[usage] => 3
[product_id] => 11
)
[2] => Array
(
[name] => Each Calendar Event
[usage] => 2
[product_id] => 14
)
[3] => Array
(
[name] => Sales Performance Dashboard
[usage] => 2
[product_id] => 30
)
[4] => Array
(
[name] => Quote
[usage] => 1
[product_id] => 32
)
)
I need an out put like this merging and adding usage values.
Array
(
[0] => Array
(
[name] => Adding An Image
[usage] => 2
[product_id] => 5
)
[1] => Array
(
[name] => Schedule A Service
[usage] => 3
[product_id] => 11
)
[2] => Array
(
[name] => Each Calendar Event
[usage] => 3
[product_id] => 14
)
[3] => Array
(
[name] => Sales Performance Dashboard
[usage] => 2
[product_id] => 30
)
[4] => Array
(
[name] => Quote
[usage] => 1
[product_id] => 32
)
[5] => Array
(
[name] => Reschedule A Service
[usage] => 1
[product_id] => 8
)
)
This is my code for creating arrays
foreach($query->rows as $product){
$top_products[]=array(
'name'=>$product['name'],
'usage'=>$product['pusage'],
'product_id'=>$product['product_id']
);
}
foreach($query_2->rows as $product){
$top_point_products[]=array(
'name'=>$product['name'],
'usage'=>$product['p_usage'],
'product_id'=>$product['product_id']
);
}
$first =array(
array(
"name" => "Reschedule A Service",
"usage" => 1,
"product_id" => 8
),
array(
"name" => "Adding An Image",
"usage" => 1,
"product_id" => 5
),
array(
"name" => "Each Calendar Event",
"usage" => 1,
"product_id" => 14
)
);
$second =array(
array(
"name" => "Adding An Image",
"usage" => 1,
"product_id" => 5
),
array(
"name" => "Schedule A Service",
"usage" => 3,
"product_id" => 11
),
array(
"name" => "Each Calendar Event",
"usage" => 2,
"product_id" => 14
),
array(
"name" => "Sales Performance Dashboard",
"usage" => 2,
"product_id" => 30
),
array(
"name" => "Quote",
"usage" => 1,
"product_id" => 32
)
);
$result = array_unique(array_merge($first,$second), SORT_REGULAR);
Use array_unique & array_merge
Use the array_merge function, like this:
$C = array_merge($A, $B);
print_r($C);
Read manual Array merge
try this code
<?php
$array1=array
(
0 => array(
'name' => "Reschedule A Service",
'usage' => 1,
'product_id' => 8
),
1 => Array
(
'name' => "Adding An Image",
'usage' => 1,
'product_id' => 5
),
2 => Array
(
'name' => "Each Calendar Event",
'usage' => 2,
'product_id' => 14
)
);
$array2=array
(
0 => Array
(
'name' => "Adding An Image",
'usage' => 1,
'product_id' => 5
),
1 => Array
(
'name' => "Schedule A Service",
'usage' => 3,
'product_id' => 11
),
2 => Array
(
'name' => "Each Calendar Event",
'usage' => 5,
'product_id' => 14
),
3 => Array
(
'name' => "Sales Performance Dashboard",
'usage' => 2,
'product_id' => 30
),
4 => Array
(
'name' => "Quote",
'usage' => 1,
'product_id' => 32
)
);
$product_id1=array_column($array1, 'product_id');
$product_id2=array_column($array2, 'product_id');
$new=array_intersect($product_id1,$product_id2);
foreach ($new as $key => $value) {
if(in_array($new[$key],$product_id2)){
$array2[array_search($new[$key],$product_id2)]['usage']+=$array1[$key]['usage'];
}
}
$new1=array_diff($product_id1,$product_id2);
foreach ($new1 as $key => $value) {
$array2[]=$array1[$key];
}
foreach ($array2 as $key => $value) {
echo "[".$key."]=><br>";
foreach ($value as $key1 => $value1) {
echo "&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp";
echo "[".$key1."]=>".$value1."<br>";
}
echo "<br>";
}
?>
output
[0]=>
[name]=>Adding An Image
[usage]=>2
[product_id]=>5
[1]=>
[name]=>Schedule A Service
[usage]=>3
[product_id]=>11
[2]=>
[name]=>Each Calendar Event
[usage]=>7
[product_id]=>14
[3]=>
[name]=>Sales Performance Dashboard
[usage]=>2
[product_id]=>30
[4]=>
[name]=>Quote
[usage]=>1
[product_id]=>32
[5]=>
[name]=>Reschedule A Service
[usage]=>1
[product_id]=>8
Use array_merge and a simple foreach loop to check your condition and update the usagevalues.
See below
$result = array_merge($arrArray1, $arrArray2);
$result2 = array();
foreach($result as $key => $value){
if(array_key_exists($value['product_id'], $result2)){
$result2[$value['product_id']]['usage'] += $value['usage'];
} else{
$result2[$value['product_id']] = $value;
}
}
print_r($result2);
If you want to reset your resultant array indexes use array_merge again like this
$result2 = array_merge($result2);
Hope this will help

Compare two array and get the difference

I've two array. $arr1 is like this:-
Array
(
[Size] => L
[Color] => Purple
[Brand] => Lee
[Fabric] => Cotton
)
and another array $arr2 is like this:-
Array
(
[0] => Array
(
[Color] => Purple
[Size] => L
[Brand] => Lee
[Fabric] => Cotton
[Price] => 1000
[Quantity] => 5
)
[1] => Array
(
[Color] => Pink
[Size] => L
[Brand] => Lee
[Fabric] => Cotton
[Price] => 1100
[Quantity] => 5
)
[2] => Array
(
[Color] => White
[Size] => L
[Brand] => Lee
[Fabric] => Cotton
[Price] => 1200
[Quantity] => 5
)
[3] => Array
(
[Color] => Black
[Size] => L
[Brand] => Lee
[Fabric] => Cotton
[Price] => 900
[Quantity] => 5
)
[4] => Array
(
[Color] => Purple
[Size] => M
[Brand] => Lee
[Fabric] => Cotton
[Price] => 900
[Quantity] => 5
)
[5] => Array
(
[Color] => Purple
[Size] => S
[Brand] => Lee
[Fabric] => Cotton
[Price] => 900
[Quantity] => 5
)
[6] => Array
(
[Color] => Pink
[Size] => M
[Brand] => Lee
[Fabric] => Cotton
[Price] => 900
[Quantity] => 5
)
[7] => Array
(
[Color] => Pink
[Size] => S
[Brand] => Lee
[Fabric] => Cotton
[Price] => 900
[Quantity] => 5
)
)
I want to get the price and quantity of $arr2 if both array matches. For example in this case $arr1 is having 4 arguments same as $arr2's 0th index values. So the resulted array should return 1000 and 5. I've tried array_diff and some other function but it doesn't helped me. Any help will be appreciated. Thanks in advance.
foreach($arr2 as $arrayIndex=>$element){
$match = true;
foreach($arr1 as $key=>$elementToMatch){
if($element[$key] != $elementToMatch ){
$match = false;
}
if($match == false) {
break;
}
}
if($match) {
return $arr2[$arrayIndex];
}
}
I would suggest something like this. It's a bit ugly becouse there is loop in a loop, but it would be easiest way to achive this.
Assuming the price and quantity is always the last, a simple approach would be this
foreach($arr2 as $arr) {
if(count(array_diff(array_slice($arr,0,4),$arr1))==0) {
return $arr;
}
}
Your
Array 1:-
$Arr1=array(array
(
"Color" => "Pink",
"Size" => "L",
"Brand" => "Lee",
"Fabric" => "Cotton",
"Price" => "1100",
"Quantity" => "5"
),array(
"Color" => "White",
"Size" => "L",
"Brand" => "Lee",
"Fabric" => "Cotton",
"Price" => "1200",
"Quantity" => "5"
),
array(
"Color" => "Black",
"Size" => "L",
"Brand" => "Lee",
"Fabric" => "Cotton",
"Price" => "1300",
"Quantity" => "5"
),
array(
"Color" => "RED",
"Size" => "L",
"Brand" => "Lee",
"Fabric" => "Cotton",
"Price" => "1100",
"Quantity" => "5"
)
);
Array 2:-
$Arr2=array
(
"Size" => "L",
"Color" => "Purple",
"Brand" => "Lee",
"Fabric" => "Cotton"
);
for($x=0;$x<sizeof($Arr1);$x++){
for($j=$x+1;$j<sizeof($Arr1);$j++){
if($Arr1[$x]["Price"]==$Arr1[$j]["Price"] && $Arr1[$x]["Quantity"]==$Arr1[$j]["Quantity"]){
$Arr2["Price"]=$Arr1[$j]["Price"];
$Arr2["Quantity"]=$Arr1[$j]["Quantity"];
}
}
}
var_dump($Arr2);
Your Output will be
'Size' => string 'L' (length=1)
'Color' => string 'Purple' (length=6)
'Brand' => string 'Lee' (length=3)
'Fabric' => string 'Cotton' (length=6)
'Price' => string '1100' (length=4)
'Quantity' => string '5' (length=1)
Assuming $arr1 is one dimensional and $arr2 is 2 dimensional, you can use following where result contains array of price and quantity for matched arrays.`
function match_array($arr1, $arr2, $result){
foreach($arr2 as $k=>$v){
// calculate diff between array1 and array2[key]
// if size of diff is 0 array matches
if(sizeof(array_diff($arr1, $v)) == 0){
// calculate the diff of array2[key] and array1
// this will give us the price and quantity
// push the diff into the result array
array_push($result, array_diff($v, $arr1));
}
}
print_r($result);
}
$result = array();
$result = match_array($array1, $array2, $result);
print_r($result);

Make array unique in multidimensional array php codeigniter

I have this array
Array (
[0] => Array
(
[0] => stdClass Object
(
[id] => 226
[user_id] => 1
[name] => Eden Corner Tub by Glass - $2099
)
[1] => stdClass Object
(
[id] => 225
[user_id] => 1
[name] => Blue Quilted Leather Jacket by Minusey - $499
)
[2] => stdClass Object
(
[id] => 222
[user_id] => 1
[name] => Darling New Bathtub by Duravit - $6300
)
)
[1] => Array
(
[0] => stdClass Object
(
[id] => 226
[user_id] => 1
[name] => Eden Corner Tub by Glass - $2099
)
[1] => stdClass Object
(
[id] => 229
[user_id] => 1
[name] => Batman Tumbler Golf Cart - $50000
)
[2] => stdClass Object
(
[id] => 228
[user_id] => 1
[name] => Swirlio Frozen Fruit Dessert Maker - $60
)
) )
I have an array of products that I need to make sure are unique.
Need to make this array unique by id. These array are generated by pushing value.
I'm trying to solve this for more than a week now, but I dont get it to work. I know it should be easy...but anyway - I don't get it :D
Try this:
$array = array(
0 => array(
"name" => "test",
"id" => 4
),
1 => array(
"name" => "test2",
"id" => 152
),
2 => array(
"name" => "test2",
"id" => 152
)
);
$newArray = array();
foreach($array as $value) {
$newArray[$value['id']]['name'] = $value['name'];
$newArray[$value['id']]['id'] = $value['id'];
}
foreach($array as $key=>$inner_array)
{
foreach($array as $key_again=>$array_again)
{
if($key != $key_again)
{
if($inner_array['name'] != $array_again['name'] AND $inner_array['id'] != $array_again['id'])
{
//its okay
}
else
{
unset($array[$key]);
}
}
}
}
Not sure how the arrays are generated, but, if you can change that, you could set the array keys to the IDs directly and check if the id is already set.
Otherwise, you can do the following:
$unique = array();
foreach( $array as $values ) {
if( ! isset( $unique[$values['id']] ) ) {
$unique[$values['id']] = $values;
}
}
This will make your array unique:
$array = array(
0 => array(
"name" => "test",
"id" => 4
),
1 => array(
"name" => "test2",
"id" => 152
),
2 => array(
"name" => "test2",
"id" => 152
) );
$result = array();
$index = array();
foreach($array as $i => $elem) {
if(!isset($index[$elem['id']])) {
$result[$i] = $elem;
$index[$elem['id']] = 1;
}
}
echo var_export($result);
Output:
array (
0 =>
array (
'name' => 'test',
'id' => 4,
),
1 =>
array (
'name' => 'test2',
'id' => 152,
),
)
This will work. It could be considered more clean than a for loop, but I'm not sure about performance.
$array = [
[ "name" => "test", "id" => 4 ],
[ "name" => "test2", "id" => 152 ],
[ "name" => "test2", "id" => 152 ]
];
array_walk($array, function(&$item, $idx) use($array){
$matches = array_slice(array_keys($array, $item), 1);
if (in_array($idx, $matches)) {
$item = false;
}
});
$array = array_filter($array);
Edit Since you updated the data set to work with, you would need to flatten it 1 level:
$array = call_user_func_array('array_merge', $array);

Categories