push array into array in specific format - php

I have this array structure named $params
Array
(
[PLANT_RA] => Array
(
[0] => Array
(
[SIGN] => I
[OPTION] => EQ
[LOW] => 6104
[HIGH] =>
)
)
[STGE_LOC_RA] => Array
(
[0] => Array
(
[SIGN] => I
[OPTION] => EQ
[LOW] => 5700
[HIGH] =>
)
)
[BATCH_RA] => Array
(
[0] => Array
(
[SIGN] => I
[OPTION] => NE
[LOW] =>
[HIGH] =>
)
)
)
which is created:
$parms2 = array(
'PLANT_RA' => array(array(
'SIGN' => "I",
'OPTION' => getOption($_GET['PLANT_RA-low'], $_GET['PLANT_RA-high']),
'LOW' => $_GET['PLANT_RA-low'],
'HIGH' => $_GET['PLANT_RA-high']
)),
'STGE_LOC_RA' => array(array(
'SIGN' => "I",
'OPTION' => getOption($_GET['STGE_LOC_RA-low'], $_GET['STGE_LOC_RA-high']),
'LOW' => $_GET['STGE_LOC_RA-low'],
'HIGH' => $_GET['STGE_LOC_RA-high']
)),
'BATCH_RA' => array(array(
'SIGN' => "I",
'OPTION' => getOption($_GET['BATCH_RA-low'], $_GET['BATCH_RA-high']),
'LOW' => $_GET['BATCH_RA-low'],
'HIGH' => $_GET['BATCH_RA-high']
))
)
However, now for my purposes I need to change it and use it via array_push(),
so I can declare empty array:
$parms2 = array();
and now when I push it in:
if (isset($_GET['PLANT_RA-low'])) {
$storage_array = array('PLANT_RA' => array(
'SIGN' => "I",
'OPTION' => getOption($_GET['PLANT_RA-low'], $_GET['PLANT_RA-high']),
'LOW' => $_GET['PLANT_RA-low'],
'HIGH' => $_GET['PLANT_RA-high']
));
array_push($parms, $storage_array);
}
if (isset($_GET['STGE_LOC_RA-low'])) {
$storage_array = array('STGE_LOC_RA' => array(
'SIGN' => "I",
'OPTION' => getOption($_GET['STGE_LOC_RA-low'], $_GET['STGE_LOC_RA-high']),
'LOW' => $_GET['STGE_LOC_RA-low'],
'HIGH' => $_GET['STGE_LOC_RA-high']
));
array_push($parms, $storage_array);
}
if (isset($_GET['BATCH_RA-low'])) {
$batch_array = array('BATCH_RA' => array(
'SIGN' => "I",
'OPTION' => getOption($_GET['BATCH_RA-low'], $_GET['BATCH_RA-high']),
'LOW' => $_GET['BATCH_RA-low'],
'HIGH' => $_GET['BATCH_RA-high']
));
array_push($parms, $batch_array);
}
then it has not correct format which is refused by SAPNWRFC:
Array
(
[0] => Array
(
[PLANT_RA] => Array
(
[SIGN] => I
[OPTION] => EQ
[LOW] => 6104
[HIGH] =>
)
)
[1] => Array
(
[STGE_LOC_RA] => Array
(
[SIGN] => I
[OPTION] => EQ
[LOW] => 5700
[HIGH] =>
)
)
[2] => Array
(
[BATCH_RA] => Array
(
[SIGN] => I
[OPTION] => NE
[LOW] =>
[HIGH] =>
)
)
)
can you please guide me how do I push (in what format) so I have the EXACT same output of the $params array at the end?

In the end all this code can be reduced to:
$parms = [];
$keys = ['PLANT_RA', 'STGE_LOC_RA', 'BATCH_RA'];
foreach ($keys as $key) {
if (isset($_GET[$key . '-low'])) {
$parms[$key] = [
[
'SIGN' => "I",
'OPTION' => getOption($_GET[$key . '-low'], $_GET[$key . '-high']),
'LOW' => $_GET[$key . '-low'],
'HIGH' => $_GET[$key . '-high']
]
];
}
}

Related

How to Filter multidimensional array and create a new array

I have this kind of array , based on Page ID like : 32,143.
I want to search if array key position have both value in it , then ignore prepend and append value and consider ONLY both value.
And if the array has NO both value and multiple prepend and append value, then it will consider based on priority key.
$sort_result = Array
(
[32] => Array
(
[0] => Array
(
[page] => 32
[position] => append
[priority] => 1
)
[1] => Array
(
[page] => 32
[position] => append
[priority] => 2
)
[2] => Array
(
[page] => 32
[position] => prepend
[priority] => 3
)
[3] => Array
(
[page] => 32
[position] => both
[priority] => 3
)
[4] => Array
(
[page] => 32
[position] => prepend
[priority] => 4
)
)
[143] => Array
(
[0] => Array
(
[page] => 143
[position] => prepend
[priority] => 19
)
[1] => Array
(
[page] => 143
[position] => prepend
[priority] => 18
)
[2] => Array
(
[page] => 143
[position] => append
[priority] => 18
)
)
)
I tried the following code , but not working :
<?php
foreach ( $modify_array as $key => $value ) {
foreach( $value as $k1 => $v1) {
if ( array_search( "both", $v1 ) ) {
$final_array[$key][$k1] = $v1;
} else{
if ( array_search( "prepend", $v1 ) ) {
$final_array[$key][$k1] = $v1;
}
if ( array_search( "append", $v1 ) ) {
$final_array[$key][$k1] = $v1;
}
}
break;
}
}
I am expecting output like this :
Array
(
[32] => Array
(
[3] => Array
(
[page] => 32
[position] => both
[priority] => 3
)
)
[143] => Array
(
[1] => Array
(
[page] => 143
[position] => prepend
[priority] => 18
)
[2] => Array
(
[page] => 143
[position] => append
[priority] => 18
)
)
)
EDIT 1 :
I manage to work , using this code
$modify_array = array();
foreach ( $sort_result as $sort_result_key => $sort_result_value ) {
$modify_array[$sort_result_value['page']][] = $sort_result_value;
}
foreach ( $modify_array as $key => $value ) {
$filter_array[$key]['both_yes'] = array_keys(array_column($value, 'position'),'both');
$filter_array[$key]['prepend_yes'] = array_keys( array_column($value, 'position'),'prepend');
$filter_array[$key]['append_yes'] = array_keys(array_column($value, 'position'),'append');
}
foreach ( $filter_array as $filter_array_key => $filter_array_value ) {
if ( ! empty( $filter_array_value['both_yes'])) {
$a = $filter_array_value['both_yes'][0];
$final_array[] = $modify_array[$filter_array_key][$a];
} else {
if ( ! empty( $filter_array_value['prepend_yes'])) {
$b = $filter_array_value['prepend_yes'][0];
$final_array[] = $modify_array[$filter_array_key][$b];
}
if ( ! empty( $filter_array_value['append_yes'])) {
$c = $filter_array_value['append_yes'][0];
$final_array[] = $modify_array[$filter_array_key][$c];
}
}
}
Edit 2 : var_export
array ( 32 => array ( 0 => array ( 'page' => '32', 'position' => 'append', 'priority' => '1', ), 1 => array ( 'page' => '32', 'position' => 'append', 'priority' => '2', ), 2 => array ( 'page' => '32', 'position' => 'prepend', 'priority' => '3', ), 3 => array ( 'page' => '32', 'position' => 'both', 'priority' => '3', ), 4 => array ( 'page' => '32', 'position' => 'prepend', 'priority' => '4', ), ), 143 => array ( 0 => array ( 'page' => '143', 'position' => 'prepend', 'priority' => '18', ), 1 => array ( 'page' => '143', 'position' => 'append', 'priority' => '18', ), 2 => array ( 'page' => '143', 'position' => 'prepend', 'priority' => '19', ), ), )
I think the lowest time complexity that I can boil this task down to uses 1 full loop of your input array followed by a loop of the grouped data with a nested loop to isolate the rows with the lowest priority value.
The first loop does the grouping and potentially sheds worthless non-both rows for a trivial memory savings.
The second loop iterates the page groups, then the inner loop favors both rows and only uses non-both rows if there are no both rows. The if and elseif ensure that only the rows with the lowest priority number are retained. I added a rsort() call with the assumption that you want prepend rows before append rows. If the position values don't need to be prioritized, then omit the condition block containing the rsort() call.
Code: (Demo)
$array = [
['page' => '32', 'position' => 'append', 'priority' => '1'],
['page' => '32', 'position' => 'append', 'priority' => '2'],
['page' => '32', 'position' => 'prepend', 'priority' => '3'],
['page' => '32', 'position' => 'both', 'priority' => '3'],
['page' => '32', 'position' => 'prepend', 'priority' => '4'],
['page' => '143', 'position' => 'prepend', 'priority' => '18'],
['page' => '143', 'position' => 'append', 'priority' => '18'],
['page' => '143', 'position' => 'prepend', 'priority' => '19'],
];
$result = [];
foreach ($array as $row) {
if (!isset($result[$row['page']])) {
$result[$row['page']] = ['both' => [], 'non-both' => []];
}
if ($row['position'] !== 'both') {
if ($result[$row['page']]['both']) {
continue; // nothing worth doing in this case, ignore the row
} else {
$result[$row['page']]['non-both'][] = $row;
}
} else {
$result[$row['page']]['both'][] = $row;
}
}
foreach ($result as $page => $rows) {
$keep = [];
foreach ($rows['both'] ?: $rows['non-both'] as $row) {
if (!$keep || $row['priority'] < $keep[0]['priority']) {
$keep = [$row];
} elseif ($row['priority'] === $keep[0]['priority']) {
$keep[] = $row;
}
}
if ($keep[0]['position'] !== 'both') {
rsort($keep); // assuming you need prepend to occur before append
}
$result[$page] = $keep;
}
var_export($result);

add or move key and value to first position in multidimensional array

I have the following array, we'll call it $arr and I have prepared a sample array. I need to manipulate the path $arr['svg'] to have a specific key and value always at index 0 position. This is a sample data-set and depending on the data I'm working with the key's and values are not fixed, however the main point is to always have the title array (key and value) at the top of the svg array.
$arr = array("svg" =>
array(
0 => array("#style" => "overflow:visible", "#xlink:href" => "test.png"),
1 => array("g" => "", "#id" => "Layer_2"),
2 => array("g" => "", "#id" => "Layer_3"),
3 => array("title" => "test")
),
"#version" => 1.2,
"#baseProfile" => "tiny-ps",
"#id" => "Layer_1",
"#xmlns" => "http://www.w3.org/2000/svg"
);
I am trying to achieve two things under the array path $arr['svg']
If the array key title exists in $arr['svg'] and it is not in index 0 position
then move it to index 0 of $arr['svg'] and shift everything else
down.
If the array key title DOES NOT exist in $arr['svg'] then add it array('title' =>
'test') to index 0 position of $arr['svg'] and shift
everything else down.
The expected output of $arr will be like so:
Array
(
[svg] => Array
(
[0] => Array
(
[title] => test
)
[1] => Array
(
[#style] => overflow:visible;
[#xlink:href] => test.png
)
[2] => Array
(
[g] =>
[#id] => Layer_2
)
[3] => Array
(
[g] =>
[#id] => Layer_3
)
)
[#version] => 1.2
[#baseProfile] => tiny-ps
[#id] => Layer_1
[#xmlns] => http://www.w3.org/2000/svg
)
I am trying to use this function to achieve this but it seems this function only works from the root array position $arr, not within a specific path $arr['svg']. If it can be modified to work within a specific path that would hopefully solve the issue.
//source: https://gist.github.com/wpscholar/0deadce1bbfa4adb4e4c
function push_at_to_associative_array($array, $key, $new ){
$keys = array_keys( $array );
$index = array_search( $key, $keys, true );
$pos = false === $index ? count( $array ) : $index + 1;
$array = array_slice($array, 0, $pos, true) + $new + array_slice($array, $pos, count($array) - 1, true);
return $array;
}
Usage:
$title = array("title" => "test');
$arr = push_at_to_associative_array($arr, 'svg', $title);
process the svg array into a new one setting [0] to the default title if we later find a title, replace svg[0]['title'] with the found one, then finally replace the original svg part of the array with the new one.
$arr = [
"svg" =>
[
["#style" => "overflow:visible", "#xlink:href" => "test.png"],
["g" => "", "#id" => "Layer_2"],
["g" => "", "#id" => "Layer_3"],
["title" => "Fred"]
],
"#version" => 1.2,
"#baseProfile" => "tiny-ps",
"#id" => "Layer_1",
"#xmlns" => "http://www.w3.org/2000/svg"
];
function push_at_to_associative_array(&$arr)
{
$new_svg = [];
foreach ($arr['svg'] as $key => $svg){
if ( $key == 0){
$new_svg[] = ['title'=>'test'];
}
if ( !array_key_exists('title', $svg) ){
$new_svg[] = $svg;
} else {
# amend title
$new_svg[0]['title'] = $svg['title'];
}
}
$arr['svg'] = $new_svg;
}
push_at_to_associative_array($arr);
print_r($arr);
RESULTS
Array
(
[svg] => Array
(
[0] => Array
(
[title] => Fred
)
[1] => Array
(
[#style] => overflow:visible
[#xlink:href] => test.png
)
[2] => Array
(
[g] =>
[#id] => Layer_2
)
[3] => Array
(
[g] =>
[#id] => Layer_3
)
)
[#version] => 1.2
[#baseProfile] => tiny-ps
[#id] => Layer_1
[#xmlns] => http://www.w3.org/2000/svg
)
And if you run it without a title in the array
$arr = [
"svg" =>
[
["#style" => "overflow:visible", "#xlink:href" => "test.png"],
["g" => "", "#id" => "Layer_2"],
["g" => "", "#id" => "Layer_3"]
],
"#version" => 1.2,
"#baseProfile" => "tiny-ps",
"#id" => "Layer_1",
"#xmlns" => "http://www.w3.org/2000/svg"
];
function push_at_to_associative_array(&$arr)
{
$new_svg = [];
foreach ($arr['svg'] as $key => $svg){
if ( $key == 0){
$new_svg[] = ['title'=>'test'];
}
if ( !array_key_exists('title', $svg) ){
$new_svg[] = $svg;
} else {
# amend title
$new_svg[0]['title'] = $svg['title'];
}
}
$arr['svg'] = $new_svg;
}
push_at_to_associative_array($arr);
print_r($arr);
RESULT
Array
(
[svg] => Array
(
[0] => Array
(
[title] => test
)
[1] => Array
(
[#style] => overflow:visible
[#xlink:href] => test.png
)
[2] => Array
(
[g] =>
[#id] => Layer_2
)
[3] => Array
(
[g] =>
[#id] => Layer_3
)
)
[#version] => 1.2
[#baseProfile] => tiny-ps
[#id] => Layer_1
[#xmlns] => http://www.w3.org/2000/svg
)
An easy solution would be to do something like this:
function fix_array( $array ) {
$svg_title_index = array_key_first(
array_filter(
$array['svg'],
fn($item) => isset($item['title'])
)
);
if (! $svg_title_index) {
array_unshift($array['svg'], ['title' => 'test']);
} elseif($svg_title_index > 0) {
$value = $array['svg'][$svg_title_index];
unset($array['svg'][$svg_title_index]);
array_unshift($array['svg'], $value);
}
return $array;
}
/* CASE 1 - SVG EXISTS BUT IS NOT FIRST */
$array = [
'svg' => [
[
'#style' => 'overflow:visible;',
'##xlink:href' => 'test.png'
],
[
'title' => 'some existing title',
],
],
'#version' => '1.2',
'#baseProfile' => 'tiny-ps',
'#id' => 'Layer_1',
'#xmlns' => 'http://www.w3.org/2000/svg'
];
print_r(fix_array( $array ));
/* CASE 2 - SVG DOES NOT EXIST */
$array = [
'svg' => [
[
'#style' => 'overflow:visible;',
'##xlink:href' => 'test.png'
]
],
'#version' => '1.2',
'#baseProfile' => 'tiny-ps',
'#id' => 'Layer_1',
'#xmlns' => 'http://www.w3.org/2000/svg'
];
print_r(fix_array( $array ));
You can see it in action here
Ok so OP want's to move the array with the title attribute to the start of the array or insert a test value if it doesn't exist.
The below function should achieve this. It might not be the most beautiful or effient but it should put you on the right track.
function order_svg_title( array $input, ?string $default_title ) {
$position = null;
// Find position of existing title (if exists).
foreach( $input[ 'svg' ] as $key => $value ) {
if ( isset( $value[ 'title' ] ) && $key !== 0 ) {
$position = $key;
}
}
// Doesn't already exist, add default title (if not null).
if ( is_null( $position ) ) {
array_unshift( $input[ 'svg' ], array( 'title' => $default_title ) );
}
// Title exists but it's in the wrong position.
else {
$value = $input[ 'svg' ][ $position ];
unset( $input[ 'svg' ][ $position ] );
array_unshift( $input[ 'svg' ], $value );
}
return $input;
}
So for this example usage would be...
$arr = array(
"svg" => array(
array(
"#style" => "overflow:visible",
"#xlink:href" => "test.png"
),
array(
array("g" => "", "#id" => "Layer_2"),
array("g" => "", "#id" => "Layer_3")
)
),
"#version" => 1.2,
"#baseProfile" => "tiny-ps",
"#id" => "Layer_1",
"#xmlns" => "http://www.w3.org/2000/svg"
);
$new_arr = order_svg_title( $arr, 'test' );
Would return:
Array
(
[svg] => Array
(
[0] => Array
(
[title] => test
)
[1] => Array
(
[#style] => overflow:visible
[#xlink:href] => test.png
)
[2] => Array
(
[0] => Array
(
[g] =>
[#id] => Layer_2
)
[1] => Array
(
[g] =>
[#id] => Layer_3
)
)
)
[#version] => 1.2
[#baseProfile] => tiny-ps
[#id] => Layer_1
[#xmlns] => http://www.w3.org/2000/svg
)
Now with an existing title:
$arr = array(
"svg" => array(
array(
"#style" => "overflow:visible",
"#xlink:href" => "test.png"
),
array(
array("g" => "", "#id" => "Layer_2"),
array("g" => "", "#id" => "Layer_3")
),
array(
"title" => "In the wrong position. I should be moved."
)
),
"#version" => 1.2,
"#baseProfile" => "tiny-ps",
"#id" => "Layer_1",
"#xmlns" => "http://www.w3.org/2000/svg"
);
$new_arr = order_svg_title( $arr, 'test' );
Would return:
Array
(
[svg] => Array
(
[0] => Array
(
[title] => In the wrong position. I should be moved.
)
[1] => Array
(
[#style] => overflow:visible
[#xlink:href] => test.png
)
[2] => Array
(
[0] => Array
(
[g] =>
[#id] => Layer_2
)
[1] => Array
(
[g] =>
[#id] => Layer_3
)
)
)
[#version] => 1.2
[#baseProfile] => tiny-ps
[#id] => Layer_1
[#xmlns] => http://www.w3.org/2000/svg
)

Print associative array to table

I have an associative array like this, i want to generate a table with these data, like breakfast, snacks, lunch, supper, dinner in row the following is the code I've tried, but I am stuck where to break the table row because when the array contains more than one item.i wants to Print associative array to table
*--------------------------------------------------*
| **Breakfast Snacks Lunch Supper Dinner** |
| test test test testfrom
|testfrom
*--------------------------------------------------*
array output is as follow
Array
(
[meal_plan_id] => 17
[calorie_limit] => 1
[total_calorie] => 0
[date] => 2017-12-29
[meal_plan] => Array
(
[0] => Array
(
[meal_type] => bf
[label] => Breakfast
[calorie_limit] => 30
[total_calorie] => 0
[data] => Array
(
[0] => Array
(
[id] => 107
[label] => test
[quantity] => 10
[unit] => g
[status] => bf
)
[1] => Array
(
[id] => 109
[label] => testfrom
[quantity] => 12
[unit] => g
)
)
)
[1] => Array
(
[meal_type] => sn
[label] => Snacks
[calorie_limit] => 10
[total_calorie] => 0
[data] => Array
(
[0] => Array
(
[id] => 108
[label] => test
[quantity] => 121
[unit] => g
)
)
)
[2] => Array
(
[meal_type] => lu
[label] => Lunch
[calorie_limit] => 20
[total_calorie] => 0
[data] => Array
(
[0] => Array
(
[status] => su
)
)
)
[3] => Array
(
[meal_type] => su
[label] => Supper
[calorie_limit] => 30
[total_calorie] => 0
[data] => Array
(
[0] => Array
(
[status] => sn
)
[1] => Array
(
[id] => 116
[label] => test
[quantity] => 200
[unit] => oz
)
)
)
[4] => Array
(
[meal_type] => dn
[label] => Dinner
[calorie_limit] => 20
[total_calorie] => 0
[data] => Array
(
[0] => Array
(
[id] => 113
[label] => test500
[quantity] => 20
[unit] => oz
[status] => dn
)
)
)
)
)
below is the code I've tried
// $daily_meals = show_daily_meals() // contains the array
if(!empty($daily_meals['meal_plan'])){
echo '<tr>';
foreach($daily_meals['meal_plan'] as $meal_plan){
foreach ($meal_plan['data'] as $data){
if(!empty($data['id']))
echo '<td class="'.$meal_type.'" data-meals-id="'.$data['id'].'"><span class="left">'.$data['label'].'</span> <span class="right">'.$data['quantity'].' <a class="delete_row"><i class="fa fa-trash" aria-hidden="true"></i></a></span><div class="row_loader"></div></td>';
else echo '<td></td>';
}
$i++;
if($i%5 == 0) echo '</tr>';
}
}
Here is your solution
Input
<?php
$array = array(
array(
'meal_type' => 'bf',
'label' => 'Breakfast',
'calorie_limit' => 30,
'total_calorie' => 0,
'data' => array(
array(
'id' => 107,
'label' => 'test',
'quantity' => 10,
'unit' => 'g',
'status' => 'bf'
),
array(
'id' => 109,
'label' => 'testfrom',
'quantity' => 12,
'unit' => 'g'
)
)
),
array(
'meal_type' => 'sn',
'label' => 'Snacks',
'calorie_limit' => 10,
'total_calorie' => 0,
'data' => array(
array(
'id' => 108,
'label' => 'test',
'quantity' => 121,
'unit' => 'g'
)
)
),
array(
'meal_type' => 'lu',
'label' => 'Lunch',
'calorie_limit' => 20,
'total_calorie' => 0,
'data' => array(array('status' => 'su'))
),
array(
'meal_type' => 'su',
'label' => 'Supper',
'calorie_limit' => 30,
'total_calorie' => 0,
'data' => array(
array('status' => 'sn'),
array(
'id' => 116,
'label' => 'test',
'quantity' => 200,
'unit' => 'oz'
),
)
),
array(
'meal_type' => 'dn',
'label' => 'Dinner',
'calorie_limit' => 20,
'total_calorie' => 0,
'data' => array(
array(
'id' => 113,
'label' => 'test500',
'quantity' => 20,
'unit' => 'oz',
'status' => 'dn'
)
)
)
);
Solution
1st foreach for parent array. Then second for its child..
foreach($array as $r){
$$r['label'] = '<table width="100%">';
foreach($r['data'] as $s){
if(isset($s['label']))$$r['label'] .= '<tr><td align="center">'.$s['label'].'</td></tr>'; // The if condition check weather the label is exist or not if yes then add that in particular label's table
}
$$r['label'] .= '</table>';
}
echo '
<table width="100%" border="1">
<thead>
<tr>
<th>Breakfast</th>
<th>Snacks</th>
<th>Lunch</th>
<th>Supper</th>
<th>Dinner</th>
</tr>
</thead>
Here all labels canverted into variable by $$r['label']. And all have there own table Now we add all these tables into the master table to get the output.
<tbody>
<tr>
<td>'.$Breakfast.'</td>
<td>'.$Snacks.'</td>
<td>'.$Lunch.'</td>
<td>'.$Supper.'</td>
<td>'.$Dinner.'</td>
</tr>
</tbody>
</table>';
//?// echo "<pre>";print_r($array);
?>
Output
Try storing all your column names in an array and create a table with it:
foreach($array as $row) {
$column[$i]['label'] = $row['label'];
$column[$i]['data'] = $this->getdata($row['data']);
$i++;
}
function getdata($array) {
$data = '';
foreach($array as $row) {
$data. = $row['label'].',';
}
return $data;
}
Create a table with the column names and try inserting data using a loop with respect to insert into

PHP array merge based on key & value

I have one array and try to change some key and value for example if sku are same than i need to merge image. Below array i have
Array
(
[0] => Array
(
[sku] => h-eldora
[name] => H ELDORA
[image] => s/files/1/1282/4221/products/h_eldora_01.jpg?v=1476667054
)
[1] => Array
(
[sku] => h-eldora
[name] =>
[image] => s/files/1/1282/4221/products/h_eldora_02.jpg?v=1475116221
)
[2] => Array
(
[sku] => h-eldora
[name] =>
[image] => s/files/1/1282/4221/products/20100707164858197_1_88da6866-701a-42b9-b523-5e454cbcce70.jpg?v=1475717598
)
[3] => Array
(
[sku] => hl-dracy
[name] => HL DRACY
[image] => s/files/1/1282/4221/products/h_dracy_01.jpg?v=1475115222
)
[4] => Array
(
[sku] => hl-dracy
[name] =>
[image] => s/files/1/1282/4221/products/h_dracy_02.jpg?v=1475115223
)
[5] => Array
(
[sku] => hl-dracy
[name] =>
[image] =>s/files/1/1282/4221/products/20100707164858197_1_633237aa-36ec-441b-a074-03844f6a0858.jpg?v=1475719793
)
)
I need to merge array like this
Array
(
[0] => Array
(
[sku] => h-eldora
[name] =>
[image1] => s/files/1/1282/4221/products/h_eldora_02.jpg?v=1475116221
[image2] => s/files/1/1282/4221/products/20100707164858197_1_88da6866-701a-42b9-b523-5e454cbcce70.jpg?v=1475717598
[image3] => s/files/1/1282/4221/products/20100707164858197_1_88da6866-701a-42b9-b523-5e454cbcce70.jpg?v=1475717598
)
[1] => Array
(
[sku] => hl-dracy
[name] => HL DRACY
[image1] => s/files/1/1282/4221/products/h_dracy_01.jpg?v=1475115222
[image2] => s/files/1/1282/4221/products/h_dracy_02.jpg?v=1475115223
[image3] => s/files/1/1282/4221/products/20100707164858197_1_633237aa-36ec-441b-a074-03844f6a0858.jpg?v=1475719793
)
)
If any php function is there than please let me know or any code suggestion
Using simple PHP:
<?php
$arr1 = array(
0 => array(
'sku' => 'h-eldora',
'name' => 'H ELDORA',
'image' => 's/files/1/1282/4221/products/h_eldora_01.jpg?v=1476667054'
),
1 => array(
'sku' => 'h-eldora',
'name' => '',
'image' => 's/files/1/1282/4221/products/h_eldora_02.jpg?v=1475116221'
),
2 => array(
'sku' => 'h-eldora',
'name' => '',
'image' => 's/files/1/1282/4221/products/20100707164858197_1_88da6866-701a-42b9-b523-5e454cbcce70.jpg?v=1475717598'
),
3 => array(
'sku' => 'hl-dracy',
'name' => 'HL DRACY',
'image' => 's/files/1/1282/4221/products/h_dracy_01.jpg?v=1475115222'
),
4 => array(
'sku' => 'hl-dracy',
'name' => 'H ELDORA',
'image' => 's/files/1/1282/4221/products/h_dracy_02.jpg?v=1475115223'
),
5 => array(
'sku' => 'hl-dracy',
'name' => 'H ELDORA',
'image' => 's/files/1/1282/4221/products/20100707164858197_1_633237aa-36ec-441b-a074-03844f6a0858.jpg?v=1475719793'
)
);
$newArr = $imgIndex = array();
foreach($arr1 as $a){
if( !array_key_exists($a['sku'],$newArr) ){
$newArr[$a['sku']] = array(
'sku' => $a['sku'],
'name' => $a['name'],
'image1' => $a['image']
);
$imgFound[$a['sku']] = 1;
}else{
$imgFound[$a['sku']]++;
$newArr[$a['sku']]['image'.$imgFound[$a['sku']]] = $a['image'];
}
}
unset($imgFound);
echo '<pre>'; print_r($newArr); echo '</pre>';
?>
This could work for you:
$data = // your input array
$uniqueSKUs = Array();
$newArray = Array();
$currentIndex = -1;
foreach ($data as $item) {
if (!in_array($item['sku'], $uniqueSKUs)) {
$currentIndex++;
$uniqueSKUs[] = $item['sku'];
$newArray[$currentIndex] = Array(
'sku' => $item['sku'],
'name' => $item['name']
);
}
$newArray[$currentIndex]['images'][] = $item['image'];
}
echo "<pre>";
var_dump($newArray);
echo "</pre>";

Compare multi-dimensional array and return missing keys in array

I have two multi-dimensional associative array ,
first we have
Array
(
[user_authentication] => Array
(
[api_user_id] => xxxxxxxxxxxxxxxxxxxxxxxx
[api_auth_token] => xxxxxxxxxxxxxxxxxxxxxx
)
[campaign_details] => Array
(
[campaign_name] => democampaign
[campaign_category] => appsGames
[campaign_sub_category] => Action
[campaign_type] => cpc
[campaign_start_date] => MM/DD/YYYY
[campaign_end_date] => MM/DD/YYYY
[campaign_start_time] => HH:mm
[campaign_end_time] => HH:mm
)
[campaign_budget_info] => Array
(
[campaign_daily_budget] => 0.2
[campaign_hourly_budget] => 0.3
[campaign_bid] => 0.1
[campaign_budget] => 1
)
[campaign_targetting_info] => Array
(
[campaign_os_type] => Apple
[country_code] => IN,AF,AG
[state_id] => Array
(
[IN] => 1,2,3
[AF] => 4,5,6
[AG] => 7,8,9
)
[carrier] => Array
(
[IN] => Tata,Aircel,RCOM,Vodafone,Airtel,Idea Cellular,Uninor,Dishnet,BSNL
[AF] =>
[AG] =>
)
[isp] =>
[device_targeting] => iphone,ipad
[conversion] =>
)
[campaign_creative_info] => Array
(
[campaign_domain] => abcd.com
[campaign_click_url] => http://url-to-redirect-users-to-after-they-click.com/
[campaign_banner_size] => URL640x1136
[campaign_banner_url] => http://imageurl.com/
[campaign_creative_type] => image
)
[campaign_black_list_white_list_info] => Array
(
[black_list_app_ids] => 5388dceb96c4b54a0844e4cb,5330b3864dab485e6219ff54
[black_list_device_ids] => aaaaaaaa-bbbb-cccc-0000-222222221111,12f93cf2-91ed-4f8f-aae7-a0520bebdd2r
[black_list_ip_addresses] => 123.123.12.123,10.100.100.100
[white_list_app_ids] => 5388dceb96c4b54a0844e4cb,5330b3864dab485e6219ff54
[white_list_device_ids] => aaaaaaaa-bbbb-cccc-0000-222222221111,12f93cf2-91ed-4f8f-aae7-a0520bebdd2r
[white_list_ip_addresses] => 123.123.12.123,10.100.100.100
)
)
and second one is which i have make to compare with
Array
(
[user_authentication] => Array
(
[api_user_id] => 1
[api_auth_token] => 1
)
[campaign_details] => Array
(
[campaign_name] => 1
[campaign_category] => 1
[campaign_sub_category] => 1
[campaign_type] => 1
[campaign_start_date] => 1
[campaign_end_date] => 1
[campaign_start_time] => 1
[campaign_end_time] => 1
)
[campaign_budget_info] => Array
(
[campaign_daily_budget] => 1
[campaign_hourly_budget] => 1
[campaign_bid] => 1
[campaign_budget] => 1
)
[campaign_targetting_info] => Array
(
[campaign_os_type] => 1
[country_code] => 1
[state_id] => Array
(
[IN] => 1
[AF] => 1
[AG] => 1
)
[carrier] => Array
(
[IN] => 1
[AF] => 1
[AG] => 1
)
[isp] => 1
[device_targeting] => 1
[conversion] => 1
)
[campaign_creative_info] => Array
(
[campaign_domain] => 1
[campaign_click_url] => 1
[campaign_banner_size] => 1
[campaign_banner_url] => 1
[campaign_creative_type] => 1
)
[campaign_black_list_white_list_info] => Array
(
[black_list_app_ids] => 1
[black_list_device_ids] => 1
[black_list_ip_addresses] => 1
[white_list_app_ids] => 1
[white_list_device_ids] => 1
[white_list_ip_addresses] => 1
)
)
we have to compare the array and find which key is missing in first array
i have tried this but not working
$comparemodel= array_diff_assoc($array1,$array2);
if($comparemodel==0){
echo "hello";
}
else{
$keys = array_keys($comparemodel);
for ($i = 0; $i < count($keys); $i++) {
$error_message[] = $keys[$i] . " is missing";
}
$model = array();
$errors = array("error_code" => 3042, "error_message" => $error_message);
$message = $error_message;
$status = 0;
$finalarray = array("modal" => $model, "errors" => $errors, "message" => $message, "status" => $status);
echo json_encode($finalarray);
}
its not working with this associative array but its working with simple array. what should i do for this.
thanks
try this code
<?php
$arr1=array("campaign_details" => array
(
"campaign_name" => "democampaign",
"campaign_category" => "appsGames",
"campaign_sub_category" => "Action",
"campaign_type" => "cpc",
"campaign_start_date" => "MM/DD/YYYY",
"campaign_end_date" => "MM/DD/YYYY",
"campaign_start_time" => "HH:mm",
"campaign_end_time" => "HH:mm"
),
"campaign_budget_info" => array
(
"campaign_daily_budget" => 0.2,
"campaign_hourly_budget" => 0.3,
"campaign_bid" => 0.1,
"campaign_budget" => 1,
),
"campaign_targetting_info" => array
(
"campaign_os_type" => "Apple",
"country_code" => "IN,AF,AG",
"state_id" => array
(
"IN" => "1,2,3",
"AF" => "4,5,6",
"AG" => "7,8,9"
),
"carrier" => Array
(
"IN" => "Tata,Aircel,RCOM,Vodafone,Airtel,Idea
Cellular,Uninor,Dishnet,BSNL",
"AF" => "",
"AG" => "",
),
"isp" => "",
"device_targeting" => "iphone,ipad",
"conversion" => "",
),
"campaign_creative_info" => array
(
"campaign_domain" => "abcd.com",
"campaign_click_url" => "http://url-to-redirect-users-to-after-
they-click.com/",
"campaign_banner_size" => "URL640x1136",
"campaign_banner_url" => "http://imageurl.com/",
"campaign_creative_type" => "image",
),
"campaign_black_list_white_list_info" => array
(
"black_list_app_ids" =>
"5388dceb96c4b54a0844e4cb,5330b3864dab485e6219ff54",
"black_list_device_ids" => "aaaaaaaa-bbbb-cccc-
0000-222222221111,12f93cf2-91ed-4f8f-aae7-a0520bebdd2r",
"black_list_ip_addresses" => "123.123.12.123,10.100.100.100",
"white_list_app_ids" =>
"5388dceb96c4b54a0844e4cb,5330b3864dab485e6219ff54",
"white_list_device_ids" => "aaaaaaaa-bbbb-cccc-
0000-222222221111,12f93cf2-91ed-4f8f-aae7-a0520bebdd2r",
"white_list_ip_addresses" => "123.123.12.123,10.100.100.100",
)
);
$arr2=array("campaign_details" =>array
(
"campaign_name" => 1,
"campaign_category" => 1,
"campaign_sub_category" => 1,
"campaign_type" => 1,
"campaign_start_date" => 1,
"campaign_end_date" => 1,
"campaign_start_time" => 1,
"campaign_end_time" => 1
),
"campaign_budget_info" => array
(
"campaign_daily_budget" => 1,
"campaign_hourly_budget" => 1,
"campaign_bid" => 1,
"campaign_budget" => 1,
),
"campaign_targetting_info" => array
(
"campaign_os_type" => 1,
"country_code" => 1,
"state_id" => array
(
"IN" => 1,
"AF" => 1,
"AG" => 1,
),
"carrier" => array
(
"IN" => 1,
"AF" => 1,
"AG" => 1,
),
"isp" => 1,
"device_targeting" => 1,
"conversion" => 1,
),
"campaign_creative_info" =>array
(
"campaign_domain" => 1,
"campaign_click_url" => 1,
"campaign_banner_size" => 1,
"campaign_banner_url" => 1,
"campaign_creative_type" => 1,
),
"campaign_black_list_white_list_info" => array
(
"black_list_app_ids" => 1,
"black_list_device_ids" => 1,
"black_list_ip_addresses" => 1,
"white_list_app_ids" => 1,
"white_list_device_ids" => 1,
"white_list_ip_addresses" => 1,
)
);
function array_keys_multi(array $array)
{
$keys = array();
foreach ($array as $key => $value) {
$keys[] = $key;
if (is_array($array[$key])) {
$keys = array_merge($keys, array_keys_multi($array[$key]));
}
}
return $keys;
}
$resArr=array();
$a=array_keys_multi($arr1);
$b=array_keys_multi($arr2);
$c=array_diff($a,$b);
if(count($c) > 0){
echo "There is differnce<br/>";
echo "<pre>";
print_r($c);
}else
echo "There is no differnce<br/>";
?>

Categories