I have 2 arrays:
first array of total transactions (haystack):
[0] => Array (
[transaction_id] => 62369600431
[invoice_number] => 37161
)
[1] => Array (
[transaction_id] => 62369595048
[invoice_number] => 37346
)
[2] => Array (
[transaction_id] => 62369537530
[invoice_number] => 38064
)
Second array of select orders (needle):
[0] => Array (
[invoice_number] => 37161
)
[1] => Array (
[invoice_number] => 37346
)
My goal is to create a third array that finds all transaction_id from the first array that have a match of order_id from the second.
I have tried array_merge and array_intersect both unsuccessfully (because I don't fully understand how to use them obviously.)
You might use array_filter and get all the invoice_numbers to check for using example array_column.
Then in the filter, check if the number occurs in the invoice_numbers using in_array.
$array1 = [
[
"transaction_id" => 62369600431,
"invoice_number" => 37161
],
[
"transaction_id" => 62369595048,
"invoice_number" => 37346
],
[
"transaction_id" => 62369600431,
"invoice_number" => 38064
]
];
$array2 = [
[
"invoice_number" => 37161
],
[
"invoice_number" => 37346
]
];
$invoiceNumbers = array_column($array2, "invoice_number");
$result = array_filter($array1, function($x) use ($invoiceNumbers) {
return in_array($x["invoice_number"], $invoiceNumbers);
});
print_r($result);
Output
Array
(
[0] => Array
(
[transaction_id] => 62369600431
[invoice_number] => 37161
)
[1] => Array
(
[transaction_id] => 62369595048
[invoice_number] => 37346
)
)
Php demo
Related
This question already has answers here:
Merging two multidimensional arrays on specific key [duplicate]
(7 answers)
Closed 4 years ago.
I got two arrays that I would like to combine based on "client_id" key (using PHP function is preferable) :
[all_client] => Array
(
[0] => Array
(
[client_id] => 1
[client_name] => Thomas Berg
[client_phone] => 12313123
[client_email] => aaaa#aaa.com
)
[1] => Array
(
[client_id] => 2
[client_name] => John Doe
[client_phone] => 4231241
[client_email] => asdas#asdas.com
)
)
[all_client_document] => Array
(
[0] => Array
(
[client_document_id] => 3
[client_document_number] => BX100
[client_document_type] => passport
[client_document_issued_date] => 2018-10-17
[client_document_expired_date] => 2018-12-02
[client_id] => 1
)
[1] => Array
(
[client_document_id] => 4
[client_document_number] => DJ200
[client_document_type] => passport
[client_document_issued_date] => 2018-10-15
[client_document_expired_date] => 2018-11-23
[client_id] => 2
)
)
)
How to merge these two array? Any PHP function to achieve this without foreach looping? I would hope to see the result as below :
[new_result] => Array
(
[0] => Array
(
[client_id] => 1
[client_name] => Thomas Berg
[client_phone] => 12313123
[client_email] => aaaa#aaa.com
[client_document_id] => 3
[client_document_number] => BX100
[client_document_type] => passport
[client_document_issued_date] => 2018-10-17
[client_document_expired_date] => 2018-12-02
)
[1] => Array
(
[client_id] => 2
[client_name] => John Doe
[client_phone] => 4231241
[client_email] => asdas#asdas.com
[client_document_id] => 4
[client_document_number] => DJ200
[client_document_type] => passport
[client_document_issued_date] => 2018-10-15
[client_document_expired_date] => 2018-11-23
)
)
How can I achieve this? Any help is much appreciated.
I found the answer based on the same question :
$first = array_column($data['all_client'], null, 'client_id');
$second = array_column($data['all_client_document'], null, 'client_id');
$result = array_values(array_replace_recursive($first, $second));
It reproduces as what I want also and simpler, thanks anyone!
You can achieve this by using array_map() function:
function make_my_data($a, $b)
{
return array_merge($a,$b);
}
$a = [
0 => [
'user_id' => 1,
'user_name' => "Ram",
],
1 => [
'user_id' => 2,
'user_name' => "Raj",
]
];
$b = [
0 => [
'user_id' => 1,
'user_emai' => "ram#abc.com",
],
1 => [
'user_id' => 2,
'user_email' => "raj#abc.com",
]
];
$d = array_map("make_my_data", $a , $b);
echo "<pre>"; print_r($d);
Output:
Array
(
[0] => Array
(
[user_id] => 1
[user_name] => Ram
[user_emai] => ram#abc.com
)
[1] => Array
(
[user_id] => 2
[user_name] => Raj
[user_email] => raj#abc.com
)
)
This question already has answers here:
How to group subarrays by a column value?
(20 answers)
Closed 2 years ago.
Is there function that works similar to array_column for multidimensional arrays? Is there a function that translates the first array below to the second:
Array
(
[0] => Array
(
[foodType] => fruits
[itemID] => 1
[itemName] => apple
)
[1] => Array
(
[foodType] => fruits
[itemID] => 2
[itemName] => banana
)
[2] => Array
(
[foodType] => veggies
[itemID] => 3
[itemName] => carrot
)
[3] => Array
(
[foodType] => veggies
[itemID] => 4
[itemName] => broccoli
)
)
Resulting array:
Array
(
[fruits] => Array
(
[0] => Array
(
[itemID] => 1
[itemName] => apple
)
[1] => Array
(
[itemID] => 2
[itemName] => banana
)
)
[veggies] => Array
(
[0] => Array
(
[itemID] => 3
[itemName] => carrot
)
[1] => Array
(
[itemID] => 4
[itemName] => broccoli
)
)
)
No, there is not a function to get your expected output natively, though you can make your own functions, just use array_column to get the types/column, and then loop over your array, on match remove the item as to not duplicate iterations.
Something like:
<?php
$data = [
['foodType' => 'fruits', 'itemID' => 1, 'itemName' => 'apple'],
['foodType' => 'fruits', 'itemID' => 2, 'itemName' => 'banana'],
['foodType' => 'veggies', 'itemID' => 3, 'itemName' => 'carrot'],
['foodType' => 'veggies', 'itemID' => 4, 'itemName' => 'broccoli']
];
function array_column_multi ($array, $column) {
$types = array_unique(array_column($array, $column));
$return = [];
foreach ($types as $type) {
foreach ($array as $key => $value) {
if ($type === $value[$column]) {
unset($value[$column]);
$return[$type][] = $value;
unset($array[$key]);
}
}
}
return $return;
}
print_r(array_column_multi($data, 'foodType'));
https://3v4l.org/KQVeN
Result:
Array
(
[fruits] => Array
(
[0] => Array
(
[itemID] => 1
[itemName] => apple
)
[1] => Array
(
[itemID] => 2
[itemName] => banana
)
)
[veggies] => Array
(
[0] => Array
(
[itemID] => 3
[itemName] => carrot
)
[1] => Array
(
[itemID] => 4
[itemName] => broccoli
)
)
)
Oh I just noticed that you're aggregating them by ID. There's not a function for that, you're going to need to iterate over the input with a loop, and populate an output array with the data you want. Eg:
$output = [];
foreach($input_array as $item) {
$output[$item['id']][] = [
'itemID' => $item['itemID'],
'itemName' => $item['itemName']
];
}
Quite old question, but I hope it help someone. Unfortunately there's no native function yet but output is achievable using php's array_filter():
$foods = [
[
'foodType' => 'fruits',
'itemID' => 1,
'itemName' => 'apple',
],
[
'foodType' => 'fruits',
'itemID' => 2,
'itemName' => 'banana',
],
[
'foodType' => 'veggies',
'itemID' => 3,
'itemName' => 'carrot',
],
[
'foodType' => 'veggies',
'itemID' => 4,
'itemName' => 'broccoli',
]
];
$grouped_foods = [];
$groupByColumn = 'foodType';
array_filter($foods, function ($foodItem) use(&$grouped_foods, $groupByColumn) {
$grouped_foods[$foodItem[$groupByColumn]][] = array_filter($foodItem, function ($key) use($groupByColumn) {
return $key != $groupByColumn;
}, ARRAY_FILTER_USE_KEY);
});
echo "<pre>";
print_R($grouped_foods);
echo "</pre>";
see in action: https://3v4l.org/bbX5A
Disclaimer: for/foreach loops are significantly faster in performance than native array functions.
I prefer using the following solution.
Example
"allergens" => array:5 [
0 => array:2 [
"id" => "10"
"object" => array:1 [
"allergens" => "10"
]
]
1 => array:2 [
"id" => "11"
"object" => array:1 [
"allergens" => "11"
]
]
2 => array:2 [
"id" => "4"
"object" => array:1 [
"allergens" => "4"
]
]
]
Giving this example, if you would like an array containing only the value of allergens then use the following code.
Solution
$allergens = array_map( function ( $ar ) {
return $ar['allergens'];
}, array_column( $allergensArr, 'object' ) );
Result
array:5 [
0 => "10"
1 => "11"
2 => "4"
]
I have tried using this example here Return index of highest value in an array
But that does not go into a multi dimensional Array
I have tried ARRAY_COLUMN(), array_values(), array_shift, Max and Min but they are not getting the info i need
I want to be able to loop thru and get to:
[pricing]
then Check pricing to see which is the highest and lowest in the nested array
so like below which total was the Highest and lowest trades on these dates
[2017-09-22]
[2017-09-23]
obviously [2017-09-23] is a simple one, i just dint want to add much more code for ppl helping to go thru.
The Array i create looks like this:
Array
(
[2017-09-23] => Array
(
[0] => Array
(
[timestamp] => 1506169387000
[pricing] => 9.5470
[qty] => 25
[total] => 238.675
[date] => 2017-09-23
)
)
[2017-09-22] => Array
(
[0] => Array
(
[timestamp] => 1506093083000
[pricing] => 9.6300
[qty] => 25
[total] => 240.75
[date] => 2017-09-22
)
[1] => Array
(
[timestamp] => 1506077220000
[pricing] => 8.7190
[qty] => 13
[total] => 113.347
[date] => 2017-09-22
)
[2] => Array
(
[timestamp] => 1506077109000
[pricing] => 8.6800
[qty] => 83
[total] => 720.44
[date] => 2017-09-22
)
[3] => Array
(
[timestamp] => 1506065258000
[pricing] => 8.7100
[qty] => 25
[total] => 217.75
[date] => 2017-09-22
)
)
in the example above i would like it to Create a new array with only the following
date -> last timestamp -> Highest pricing -> Lowest lowest -> Total of all Totals -> first Timestamp
EDIT: the last and first Timestamp are basically the first and last index so in this case:
[timestamp] => 1506093083000 and [timestamp] => 1506065258000
or Index [0] and index [3]
The array from your question:
$array = array (
'2017-09-23' =>
array (
0 =>
array (
'timestamp' => '1506169387000',
'pricing' => '9.5470',
'qty' => '25',
'total' => '238.675',
'date' => '2017-09-23',
),
),
'2017-09-22' =>
array (
0 =>
array (
'timestamp' => '1506093083000',
'pricing' => '9.6300',
'qty' => '25',
'total' => '240.75',
'date' => '2017-09-22',
),
1 =>
array (
'timestamp' => '1506077220000',
'pricing' => '8.7190',
'qty' => '13',
'total' => '113.347',
'date' => '2017-09-22',
),
2 =>
array (
'timestamp' => '1506077109000',
'pricing' => '8.6800',
'qty' => '83',
'total' => '720.44',
'date' => '2017-09-22',
),
3 =>
array (
'timestamp' => '1506065258000',
'pricing' => '8.7100',
'qty' => '25',
'total' => '217.75',
'date' => '2017-09-22',
),
),
);
To get the values maybe you can use array_map and with this the function array_column is the key of all, try with this:
$values = array_map(function($dates) {
$timestamps = array_column($dates, 'timestamp');
$pricings = array_column($dates, 'pricing');
return [
'max_pricing' => max($pricings),
'lowest_pricing' => min($pricings),
'total_of_totals' => array_sum(array_column($dates, 'total')),
'first_timestamp' => reset($timestamps),
'last_timestamp' => end($timestamps),
];
}, $array);
$values is an array with the filter values that you need:
Array
(
[2017-09-23] => Array
(
[max_pricing] => 9.5470
[lowest_pricing] => 9.5470
[total_of_totals] => 238.675
[first_timestamp] => 1506169387000
[last_timestamp] => 1506169387000
)
[2017-09-22] => Array
(
[max_pricing] => 9.6300
[lowest_pricing] => 8.6800
[total_of_totals] => 1292.287
[first_timestamp] => 1506093083000
[last_timestamp] => 1506065258000
)
)
EDIT
Get the pricing of the [first_timestamp] and [last_timestamp]
$values = array_map(function($dates) {
$timestamps = array_column($dates, 'timestamp');
$pricings = array_column($dates, 'pricing');
return [
'max_pricing' => max($pricings),
'lowest_pricing' => min($pricings),
'total_of_totals' => array_sum(array_column($dates, 'total')),
'first_timestamp' => [
'value' => reset($timestamps),
'pricing' => $pricings[each($timestamps)['key']]
],
'last_timestamp' => [
'value' => end($timestamps),
'pricing' => $pricings[each($timestamps)['key']]
]
];
}, $array);
I added an array to both timestamps with the value of these and the pricing.
Array
(
[2017-09-23] => Array
(
[max_pricing] => 9.5470
[lowest_pricing] => 9.5470
[total_of_totals] => 238.675
[first_timestamp] => Array
(
[value] => 1506169387000
[pricing] => 9.5470
)
[last_timestamp] => Array
(
[value] => 1506169387000
[pricing] => 9.5470
)
)
[2017-09-22] => Array
(
[max_pricing] => 9.6300
[lowest_pricing] => 8.6800
[total_of_totals] => 1292.287
[first_timestamp] => Array
(
[value] => 1506093083000
[pricing] => 9.6300
)
[last_timestamp] => Array
(
[value] => 1506065258000
[pricing] => 8.7100
)
)
)
I am stuck on this i have multiple associative array and i want to convert in to one:-
Here is the array:-
Array
(
[0] => Array
(
[0] => Women
)
[1] => Array
(
[0] => children
[1] => smile
)
[2] => Array
(
[0] => Abstract
)
[3] => Array
(
[0] => Lion
[1] => Cheetah
)
)
I want output something like this:-
Array
(
[0] => Women
[1] => children
[2] => smile
[3] => Abstract
[4] => Lion
[5] => Cheetah
)
Here i have tried so far:-
$getKeywords = DB::table('contributor_images')->select('keywords')->get();
$getKeywords = json_decode(json_encode($getKeywords),true);
foreach($getKeywords as $keyword){
$AllKeywords[] = $keyword['keywords'];
}
foreach ($AllKeywords as $key => $ExplodeKeywords) {
$searchkeywords[] = explode(',',$ExplodeKeywords);
}
echo "<pre>"; print_r($searchkeywords); die;
I am using laravel framework of php. THANKS IN ADVANCE :)
You can use Laravel helper function array_flatten for this:
$array = [
0 => [
0 => 'Women',
],
1 => [
0 => 'children',
1 => 'smile',
],
2 => [
0 => 'Abstract',
],
3 => [
0 => 'Lion',
1 => 'Cheetah',
],
];
$result = array_flatten($array);
var_dump($result);
Output:
array (size=6)
0 => string 'Women' (length=5)
1 => string 'children' (length=8)
2 => string 'smile' (length=5)
3 => string 'Abstract' (length=8)
4 => string 'Lion' (length=4)
5 => string 'Cheetah' (length=7)
Try this:
foreach ($old as $data) {
foreach ($data as $value) {
$new[] = $value;
}
}
print_r($new);
}
In first foreach you are getting array inside array and in second foreach you will get the value. Insert these values in new array to get desired result. Use print_r to see the result
Simply you can use : call_user_func_array
<?php
$array = array (
0 =>
array (
0 => 'Women',
),
1 =>
array (
0 => 'children',
1 => 'smile',
),
2 =>
array (
0 => 'Abstract',
),
3 =>
array (
0 => 'Lion',
1 => 'Cheetah',
),
);
$result = call_user_func_array('array_merge', $array);
print_r($result);
?>
Output :
Array
(
[0] => Women
[1] => children
[2] => smile
[3] => Abstract
[4] => Lion
[5] => Cheetah
)
Check here : https://eval.in/829111
Ref : http://php.net/manual/en/function.call-user-func-array.php
Since Laravel 5.7 the syntax is Arr::flatten($array) so that now it looks like
use Illuminate\Support\Arr;
$array = [
0 => [
0 => "Women"
],
1 => [
0 => 'children',
1 => 'smile'
],
2 => [
0 => 'Abstract'
],
3 => [
0 => 'Lion',
1 => 'Cheetah'
]
];
Arr::flatten($array);
Output :
array:6 [
0 => "Women"
1 => "children"
2 => "smile"
3 => "Abstract"
4 => "Lion"
5 => "Cheetah"
]
Docs be here
im using yii2 framework
I have array coming from controller to the view.
public function actionProducts()
{
$product = Yii::$app->httpclient->get('http://localhost/MWSProducts/src/MarketplaceWebServiceProducts/Samples/GetMatchingProductSample.php');
$array1 = str_replace("ns2:","",$product);
$array=json_decode(json_encode(simplexml_load_string($array1)),true);
return $this->render('products',['array'=>$array]);
}
In the above code im converting xml to an array.
The $array has the array, and im passing it to view called products. Now i want to display that array in the view in Gridview, Since im new to yii2 im unable to do this, it says i have to use some dataprovider, but im not getting how to do this.
Can anyone please help me in this how do i display the array in gridview. Thank you
Thanks for the answer..
Actually its a amazon product array im fetching it from the Product API, we cant define any predefine attributes like id and all, since its different for each product. this is how the array looks like.
Array
(
[GetMatchingProductResult] => Array
(
[0] => Array
(
[#attributes] => Array
(
[ASIN] => 0886467918
[status] => Success
)
[Product] => Array
(
[Identifiers] => Array
(
[MarketplaceASIN] => Array
(
[MarketplaceId] => A21TJRUUN4KGV
[ASIN] => 0886467918
)
)
[AttributeSets] => Array
(
[ItemAttributes] => Array
(
[Author] => Kipling, Rudyard
[Binding] => Hardcover
[Edition] => Har/Cas
[Format] => Import
[Label] => Imprint unknown
[Languages] => Array
(
[Language] => Array
(
[0] => Array
(
[Name] => english
[Type] => Published
)
[1] => Array
(
[Name] => english
[Type] => Original Language
)
[2] => Array
(
[Name] => english
[Type] => Unknown
)
)
)
[Manufacturer] => Imprint unknown
[PackageDimensions] => Array
(
[Weight] => 1.74
)
[ProductGroup] => Book
[ProductTypeName] => ABIS_BOOK
[PublicationDate] => 1988-05-02
[Publisher] => Imprint unknown
[SmallImage] => Array
(
[URL] => http://ecx.images-amazon.com/images/I/412CsE6Mb8L._SL75_.jpg
[Height] => 75
[Width] => 50
)
[Studio] => Imprint unknown
[Title] => Jungle Book ("Read Along")
)
)
[Relationships] => Array
(
)
[SalesRankings] => Array
(
[SalesRank] => Array
(
[0] => Array
(
[ProductCategoryId] => book_display_on_website
[Rank] => 709468
)
[1] => Array
(
[ProductCategoryId] => 1318084031
[Rank] => 14260
)
[2] => Array
(
[ProductCategoryId] => 1318083031
[Rank] => 47016
)
)
)
)
)
If the array contain the data like a dataProvider . you can use arrayDataProvider http://www.yiiframework.com/doc-2.0/yii-data-arraydataprovider.html eg (from yii2 guide):
$data = [
['id' => 1, 'name' => 'name 1', ...],
['id' => 2, 'name' => 'name 2', ...],
...
['id' => 100, 'name' => 'name 100', ...],
];
$provider = new ArrayDataProvider([
'allModels' => $data,
'pagination' => [
'pageSize' => 10,
],
'sort' => [
'attributes' => ['id', 'name'],
],
]);
a brief guide to dataprovider http://www.yiiframework.com/doc-2.0/guide-output-data-providers.html
in your case
public function actionProducts()
{
$product = Yii::$app->httpclient->get('http://localhost/MWSProducts/src/MarketplaceWebServiceProducts/Samples/GetMatchingProductSample.php');
$array1 = str_replace("ns2:","",$product);
$array=json_decode(json_encode(simplexml_load_string($array1)),true);
$provider = new ArrayDataProvider([
'allModels' => $array,
'pagination' => [
'pageSize' => 10,
],
]);
return $this->render('products',['array'=>$array]);
}
Refer to sample above where the array $data contain id, name and suppose your arrayDataProvider is in the var $array and have id,name too in gridview you should have
<?= GridView::widget([
'dataProvider' => $array,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'name',
.....
['class' => 'yii\grid\ActionColumn',
'contentOptions' => ['style' => 'width:84px; font-size:18px;']],
],
]); ?>