I need to make an array like this
$preferenceData = [
'items' => [
[
'id' => 1,
'title' => 'Recarga de Créditos',
'description' => 'Recarga de Créditos para Negocioson.com',
'quantity' => 1,
'currency_id' => 'ARS',
'unit_price' => $amount
]
]
];
But I need to create it with a foreach
foreach ($items as $item) {
}
I tried this:
$data[0]['items'][0]['id'] = 1;
BUT the results are not the same:
This is mine:
Array ( [0] => Array ( [items] => Array ( [0] => Array ( [id] => 1 ) ) ) )
This is the preference one:
Array ( [items] => Array ( [0] => Array ( [id] => 1 ) ) )
I add a [0] how can I delete it?
Thanks
You shouldn't use $data[0]. The top-level array is an associative array, not numeric.
$data['items'][0] = [
'id' => 1,
'title' => 'Recarga de Créditos',
'description' => 'Recarga de Créditos para Negocioson.com',
'quantity' => 1,
'currency_id' => 'ARS',
'unit_price' => $amount
];
You can do something like:
$data = [];
foreach ($items as $item) {
$data['items'][] = [
'id' => $item['id'],
'title' => $item['title'],
...
];
}
Related
I want to modify the existing array to a particular format please see the below array what i have and what i want
I have array as :
Array
(
[0] => Array
(
[block_id] => 1
[title] => Test1
[identifier] => test1
[content] => some test data
[creation_time] => 2019-09-03 09:47:35
[update_time] => 2019-09-03 09:47:35
[is_active] => 1
)
[1] => Array
(
[block_id] => 2
[title] => test2
[identifier] => twst2
[content] => dfdsffsdfsdfsfsdf
[creation_time] => 2019-09-03 09:48:03
[update_time] => 2019-09-03 09:48:03
[is_active] => 1
)
)
And I want this array as :
$options = [
['value' => 'test1', 'label' => __('Test1')],
['value' => 'test2', 'label' => __('Test2')],
['value' => 'test3', 'label' => __('Test3')],
['value' => 'test4', 'label' => __('Test4')],
['value' => 'test5', 'label' => __('Test5')],
['value' => 'test6', 'label' => __('Test6')]
];
Try this Solution.
$data = Array ( Array
(
'block_id' => 1,
'title' => 'Test1'
), Array
(
'block_id' => 2,
'title' => 'test2'
)
);
foreach($data as $k => $val){
$options[$k]['value'] = $val['title'];
$options[$k]['label'] = '__("'.ucfirst($val['title']).'")';
}
echo "<pre>";
print_r( $options);
Expected Result is
Array
(
[0] => Array
(
[value] => Test1
[label] => __("Test1")
)
[1] => Array
(
[value] => test2
[label] => __("Test2")
)
)
If $array is your array, then
foreach ($array as $k => $v)
{
$options[] = [ 'value' => $v['identifier'], 'label' => "__('" . $v['title'] . "')"];
}
If you are trying "to modify the existing array to a particular format" , next approach may help. When you precede $value with &, the $value will be assigned by reference and you can directly modify it.
<?php
foreach($array as &$value) {
$value = array(
'value' => $value["identifier"],
'label' => "__('".$value["title"]."')"
);
};
unset($value);
?>
Try this Solution.
foreach ($array as $k => $val)
{
$options[] = [ 'val' => $val['identifier'], 'label' => "__('" . $val['title'] . "')"];
}
This question already has answers here:
Merge arrays of associative arrays by shared column values [duplicate]
(3 answers)
Closed 5 months ago.
I have 2 array like follows:
$array1 = [
'0' => [
'no_invoice' => 'INV0001',
'product_code' => '1111111',
],
'1' => [
'no_invoice' => 'INV0001',
'product_code' => '1111112',
]
];
$array2 = [
'0' => [
'product_code' => '1111112',
'free_valie' => 839,
'count' => 1240
],
];
Is it possible to combine arrays above to be like this:
Array(
[0] => Array
(
'no_invoice' => 'INV0001',
'product_code' => '1111111',
)
[1] => Array
(
'no_invoice' => 'INV0001',
'product_code' => '1111112',
'free_valie' => 839,
'count' => 1240
)
)
So, if array have same product code, then it will join like the example above.
I have been tried with use array merge, array_merge($array1, $array2);
But the result is like this:
Array(
[0] => Array
(
'no_invoice' => 'INV0001',
'product_code' => '1111111',
)
[1] => Array
(
'no_invoice' => 'INV0001',
'product_code' => '1111112',
)
[2] => Array
(
'product_code' => '1111112',
'free_valie' => 839,
'count' => 1240
)
)
This code will do what you want. It loops over each value in $array1, using array_search to see if the entrie's product_code is also present in $array2 (by looking through the product_code column of $array2 extracted using array_column). If it is, the values are merged. Note that we use &$val in the foreach, causing the value to be passed by reference which allows it to be modified in the loop
foreach ($array1 as &$val) {
if (($k = array_search($val['product_code'], array_column($array2, 'product_code'))) !== false) {
$val = array_merge($val, $array2[$k]);
}
}
print_r($array1);
Output:
Array
(
[0] => Array
(
[no_invoice] => INV0001
[product_code] => 1111111
)
[1] => Array
(
[no_invoice] => INV0001
[product_code] => 1111112
[free_valie] => 839
[count] => 1240
)
)
Demo on 3v4l.org
Try below one.
$array1 = [
'0' => [
'no_invoice' => 'INV0001',
'product_code' => '1111111',
],
'1' => [
'no_invoice' => 'INV0001',
'product_code' => '1111112',
]
];
$array2 = [
'0' => [
'product_code' => '1111112',
'free_valie' => 839,
'count' => 1240
],
];
foreach ($array1 as $key => &$value) {
$key = array_search($value['product_code'], array_column($array2, 'product_code'));
if ($key !== false) {
$value = array_merge($value, $array2[$key]);
unset($array2[$key]);
$array2 = array_values($array2);
}
}
echo '<pre>';
print_r($array1);
exit;
The task is to merge ("inexpensively") two arrays, which have matching key-value pairs of subarrays. E.g.:
Array 1:
Array
(
[0] => Array
(
[count] => 1
[da_table] => article
[da_class] => classes\elements\tables\Article
[da_page_class] => Page_Article
)
[1] => Array
(
[count] => 2
[da_table] => client_contract_specification_price
[da_class] => classes\elements\tables\ClientContractSpecificationPrice
[da_page_class] => Page_ClientContractSpecification
)
[2] => Array
(
[count] => 2
[da_table] => supplier
[da_class] => classes\elements\tables\Supplier
[da_page_class] => Page_Supplier
)
)
Array 2:
Array
(
[0] => Array
(
[name] => Articles
[name_short] =>
[da_page_class] => Page_Article
)
[1] => Array
(
[name] => Client contract specifications
[name_short] => cc_specifications
[da_page_class] => Page_ClientContractSpecification
)
[2] => Array
(
[name] => Suppliers
[name_short] =>
[da_page_class] => Page_Supplier
)
)
How to merge the two above arrays by a matching [da_page_class] => ... pairs, so the resulting array will contain both key-values of the first and the second array, i.e.:
...
[0] => Array
(
[count] => 1
[da_table] => article
[da_class] => classes\elements\tables\Article
[da_page_class] => Page_Article
[name] => Articles
[name_short] =>
)
...
Additional requirements:
Subarrays may come in random order. Also, there can be "orphans", which contain values of ['da_page_class'], but have no match in another array. These should be ignored.
Well, you simply iterate over the array elements and combine them:
<?php
$data1 = [
[
'count' => 1,
'da_table' => 'article',
'da_class' => 'classes\elements\tables\Article',
'da_page_class' => 'Page_Article'
],
[
'count' => 2,
'da_table' => 'client_contract_specification_price',
'da_class' => 'classes\elements\tables\ClientContractSpecificationPrice',
'da_page_class' => 'Page_ClientContractSpecification'
],
[
'count' => 2,
'da_table' => 'supplier',
'da_class' => 'classes\elements\tables\Supplier',
'da_page_class' => 'Page_Supplier'
]
];
$data2 = [
[
'name' => 'Articles',
'name_short' => null,
'da_page_class' => 'Page_Article'
],
[
'name' => 'Client contract specifications',
'name_short' => 'cc_specifications',
'da_page_class' => 'Page_ClientContractSpecification'
],
[
'name' => 'Suppliers',
'name_short' => null,
'da_page_class' => 'Page_Supplier'
]
];
$output = [];
for ($i=0; $i<count($data1); $i++) {
$output[$i] = array_merge($data1[$i], $data2[$i]);
}
print_r($output);
The output obviously is:
Array
(
[0] => Array
(
[count] => 1
[da_table] => article
[da_class] => classes\elements\tables\Article
[da_page_class] => Page_Article
[name] => Articles
[name_short] =>
)
[1] => Array
(
[count] => 2
[da_table] => client_contract_specification_price
[da_class] => classes\elements\tables\ClientContractSpecificationPrice
[da_page_class] => Page_ClientContractSpecification
[name] => Client contract specifications
[name_short] => cc_specifications
)
[2] => Array
(
[count] => 2
[da_table] => supplier
[da_class] => classes\elements\tables\Supplier
[da_page_class] => Page_Supplier
[name] => Suppliers
[name_short] =>
)
)
Alternatively you could also merge the contents of the elements of the second array into the corresponding elements of the first array. That reduces the memory footprint for large data sets.
Considering the additional requirement you specified in your comment I changed the merge strategy to allow for arbitrary orders of the two sets:
<?php
$data1 = [
[
'count' => 1,
'da_table' => 'article',
'da_class' => 'classes\elements\tables\Article',
'da_page_class' => 'Page_Article'
],
[
'count' => 2,
'da_table' => 'client_contract_specification_price',
'da_class' => 'classes\elements\tables\ClientContractSpecificationPrice',
'da_page_class' => 'Page_ClientContractSpecification'
],
[
'count' => 2,
'da_table' => 'supplier',
'da_class' => 'classes\elements\tables\Supplier',
'da_page_class' => 'Page_Supplier'
]
];
$data2 = [
[
'name' => 'Articles',
'name_short' => null,
'da_page_class' => 'Page_Article'
],
[
'name' => 'Client contract specifications',
'name_short' => 'cc_specifications',
'da_page_class' => 'Page_ClientContractSpecification'
],
[
'name' => 'Suppliers',
'name_short' => null,
'da_page_class' => 'Page_Supplier'
]
];
$output = [];
array_walk($data1, function($entry, $key) use (&$output, $data2) {
$output[$key] = $entry;
foreach($data2 as $cand) {
if ($entry['da_page_class'] == $cand['da_page_class']) {
$output[$key] = array_merge($output[$key], $cand);
}
}
});
print_r($output);
The resulting output obviously is identical to above.
O(m*n) solution:
$result = array();
foreach ($array1 as $value1) {
// do not handle elements without pageclass
if (!array_key_exists('da_page_class', $value1) || !$value1['da_page_class']) {
continue;
}
foreach ($array2 as $value2) {
if (!array_key_exists('da_page_class', $value2) || !$value2['da_page_class']) {
continue;
}
if ($value1['da_page_class'] == $value2['da_page_class']) {
array_push($result, $value1 + $value2)
break;
}
}
}
print_r($result);
O(m+n) solution:
$result = array();
foreach ($array1 as $value) {
// do not handle elements without pageclass
if (!array_key_exists('da_page_class', $value) || !$value['da_page_class']) {
continue;
}
$result[$value['da_page_class']] = $value;
}
foreach ($array2 as $value) {
if (
// do not handle elements without pageclass
!array_key_exists('da_page_class', $value) || !$value['da_page_class'] ||
// do not handle elements that do not exist in array 1
!array_key_exists($value['da_page_class'], $result)
) {
continue;
}
// merge values of this pageclass
$result[$value['da_page_class']] = array_merge($result[$value['da_page_class']], $value);
}
print_r($result);
EDIT: added O(m+n) solution
The following array is coming on $output variable,
Array
(
[title] => Subtotal
[data] => $1,104.05
)
Array
(
[title] => Total Shipping
[data] => $56.45
)
Array
(
[title] => Order total
[data] => $1,160.50
)
Array
(
[border] => top
[title] => Paying by
[data] => PayPal
)
I want to separate the following array from the above array and want to store it on new variable.
Note:Arrays are coming dynamic.
Array
(
[title] => Order total
[data] => $1,160.50
)
Please help!!
Try this,
$array = array(
Array
(
[title] => Subtotal
[data] => $1,104.05
)
Array
(
[title] => Total Shipping
[data] => $56.45
)
Array
(
[title] => Order total
[data] => $1,160.50
)
Array
(
[border] => top
[title] => Paying by
[data] => PayPal
)
);
$second_array = array();
foreach($array as $key => $arr){
if(isset($arr['title']) && $arr['title'] === 'Order total'){
$second_array = $arr;
unset($array[$key]);
}
}
This code will check title key is set or not and it's value
$array = [
[
'title' => 'Subtotal',
'data' => '$1,104.05'
],
[
'title' => 'Total Shipping',
'data' => '$56.45'
],
[
'title' => 'Order total',
'data' => '$1,160.50'
],
[
'border' => 'top',
'title' => 'Paying by',
'data' => 'PayPal'
]
];
for($i = 0; $i<=count($array); $i){
if(isset($array[$i]['title']) && $arr[$i]['title'] === 'Order total'){
$newarr = $arr;
unset($array[$key]);
}
}
You should use array_filter().
$array = [
[
'title' => 'Subtotal',
'data' => '$1,104.05'
],
[
'title' => 'Total Shipping',
'data' => '$56.45'
],
[
'title' => 'Order total',
'data' => '$1,160.50'
],
[
'border' => 'top',
'title' => 'Paying by',
'data' => 'PayPal'
]
];
$array = array_filter($array, function($ar) {
return ($ar['title'] == 'Order total'); //check condition and return record with key
});
$newArray = []; // your new array
$key = key($array); // get key of result array
$newArray = $array[$key]; // assign result record to new array
echo "<pre>"; print_r($newArray);
output:-
Array
(
[title] => Order total
[data] => $1,160.50
)
Hope it will help you :-)
Scenario:
I have these 2 arrays:
array1:
Array
(
[1] => Array
(
[label] => pending
[fillColor] => #468847
[data] => 50
)
[2] => Array
(
[label] => dispatched
[fillColor] => #6ecf70
[data] => 10
)
[3] => Array
(
[label] => delivered
[fillColor] => #f89406
[data] => 1
)
[4] => Array
(
[label] => invoiced
[fillColor] => #3a87ad
[data] => 2
)
)
array2:
Array
(
[1] => Array
(
[label] => pending
[fillColor] => #468847
[data] => Array
(
[0] => 1
)
)
)
The result I need is
Array
(
[1] => Array
(
[label] => pending
[fillColor] => #468847
[data] => Array
(
[0] => 50
[1] => 1
)
)
[2] => Array
(
[label] => dispatched
[fillColor] => #6ecf70
[data] => Array
(
[0] => 10
[1] => 0
)
)
[3] => Array
(
[label] => delivered
[fillColor] => #f89406
[data] => Array
(
[0] => 1
[1] => 0
)
)
[4] => Array
(
[label] => invoiced
[fillColor] => #3a87ad
[data] => Array
(
[0] => 2
[1] => 0
)
)
)
There are only 4 labels:
pending
dispatched
delivered
invoiced
Please note that the arrays are just an example. It can happen that the first array has no values at all or just 2 and the second array have 3 values or none.
Because of that constraint above I'm thinking to use array_replace and having an array called
base_array = ["pending", "dispatched", "delivered", "invoiced"]
I have tried to loop the base_array and try to match the array1 with array2 if label exist.
Basically, if key (which is label) is not exist in any of array1 or array2 then the value replaced will be 0 in the resulting array.
I have tried
foreach($base_array as $key => $value) {
if(in_array($key, $array1[$key])) {
$array[$key] = $array1[$key];
}
}
but it looks like I'm lost on these multi dimensional arrays and replacing. Any help will be really appreciated. Thanks.
From what i understand from your question you can do it like this :-
$array = array(
'1' => Array
(
'label' => 'pending',
'fillColor' => '#468847',
'data' => '50'
),
'2' => Array
(
'label' => 'dispatched',
'fillColor' => '#6ecf70',
'data' => '10'
),
'3 ' => Array
(
'label' => 'delivered',
'fillColor' => '#f89406',
'data' => '1'
),
'4' => Array
(
'label' => 'invoiced',
'fillColor' => '#3a87ad',
'data' => '2'
),
);
$array2 = array
(
'1' => Array
(
'label' => 'pending',
'fillColor' => '#468847',
'data' => array
(
'0' => '1'
)
)
);
$temp = array();
$i = 0;
foreach ($array as $key => $value) {
$temp[$key]['label'] = $value['label'];
$temp[$key]['fillColor'] = $value['fillColor'];
foreach ($array2 as $key2 => $value2) {
if ($value['fillColor'] == $value2['fillColor'] && $value['label'] == $value2['label']) {
$temp[$key]['data'][] = $value['data'];
if (isset($value2['data'][$i])) {
$temp[$key]['data'][] = $value2['data'][$i];
}
} else {
$temp[$key]['data'][] = $value['data'];
if (!isset($value2['data'][$i])) {
$temp[$key]['data'][] = 0;
}
}
$i++;
}
}
echo '<pre>';
print_r($temp);
Try this out:
$array1 = array(
array(
'label' => 'pending',
'fillColor' => '#468847',
'data' => '50'
),
array(
'label' => 'dispatched',
'fillColor' => '#468847',
'data' => '10'
),
array(
'label' => 'delivered',
'fillColor' => '#468847',
'data' => '8'
),
array(
'label' => 'invoiced',
'fillColor' => '#468847',
'data' => '5'
)
);
$array2 = array(
array(
'label' => 'pending',
'fillColor' => '#468847',
'data' => array()
),
array(
'label' => 'dispatched',
'fillColor' => '#6ecf70',
'data' => array()
),
array(
'label' => 'delivered',
'fillColor' => '#f89406',
'data' => array()
),
array(
'label' => 'invoiced',
'fillColor' => '#3a87ad',
'data' => array()
)
);
foreach ($array1 as $order) {
foreach ($array2 as $key => $group) {
if ($order['label'] == $group['label']) {
array_push($array2[$key]['data'], $order['data']);
}
}
}
var_dump($array2);
Declare an array of default rows with empty data values.
Merge the default array, the first array, thrn the second array into one array.
Iterate the merged array's rows.
Declare reference arrays which are identified by label values. Explicitly cast each encountered data value as an array before joining into its group's subarray.
Code: (Demo)
$defaults = [
['label' => 'pending', 'fillColor' => '#468847', 'data' => []],
['label' => 'dispatched', 'fillColor' => '#6ecf70', 'data' => []],
['label' => 'delivered', 'fillColor' => '#f89406', 'data' => []],
['label' => 'invoiced', 'fillColor' => '#3a87ad', 'data' => []],
];
$result = [];
foreach (array_merge($defaults, $array1, $array2) as $row) {
$label = $row['label'];
$row['data'] = (array) $row['data'];
if (!isset($ref[$label])) {
$ref[$label] = $row;
$result[] = &$ref[$label];
} else {
$ref[$label]['data'] = array_merge(
$ref[$label]['data'],
$row['data']
);
}
}
var_export($result);