Add New/Update $key and $value to an Array in WordPress - arrays

I am trying to add/update a new $key and $value to an existing array.
Form input:
<input name="flyer_packages[55][price][custom_price]" value="1000">
Current Array:
Array (
[55] => Array (
[date] => 10 October
[pricing_option] => true
[price] => Array (
[price_amount] => 3 000
[price_descriptor] => None
WP function to add new meta:
if (!empty ($_POST['flyer_packages'])) {
$flyer_packages = get_post_meta($pid, 'flyer_packages', true);
foreach ($flyer_packages as $flyer_package) {
foreach ($flyer_package[price] as $key => $value) {
update_post_meta( $pid, 'flyer_packages' , $_POST['flyer_packages']);
}
}
}
Expected Result:
Array (
[55] => Array (
[date] => 10 October
[pricing_option] => true
[price] => Array (
[price_amount] => 3 000
[price_descriptor] => None
[custom_price] => 1 000
Actual Result:
Array (
[55] => Array (
[price] => Array (
[custom_price] => 1 000
As you can see the result adds the new key and value but deletes all other keys and values in the array.
Can anybody please advise, much appreciated.

It happens because you're replacing the value, you have to merge arrays first
if (!empty ($_POST['flyer_packages'])) {
$flyer_packages = get_post_meta($pid, 'flyer_packages', true);
$new_value = $_POST['flyer_packages'];
custom_keys_recursive($new_value, $flyer_packages);
update_post_meta( $pid, 'flyer_packages', $flyer_packages);
}
function custom_keys_recursive($value, &$array) {
foreach ($value as $k=>$v) {
if (is_array($v)) {
custom_keys_recursive($v, $array[$k]);
} else {
$array[$k] = $v;
}
}
}

Related

How to remove first dimension of an array without loosing keys?

How can i remove the first dimansion of a multidemensional Array without loosing the keys?
i have an Array that have multiple arrays inside
the firstkey is a Date and the secondkey is the hour.
my Output is:
Array
(
[0] => Array
(
[firstkey] => Array
(
[secondkey] => Array
(
[0] => 7
[1] => 8
)
)
)
[1] => Array
(
[firstkey] => Array
(
[secondkey] => Array
(
[0] => 7
[1] => 8
)
)
)
)
and i want this:
Array
(
[firstkey] => Array
(
[secondkey] => Array
(
[0] => x
[1] => y
[2] => z
[3] => r
)
)
)
i also tried array_merge_recursive() but instead of putting the values to the secondkey it creates a new array with an incremental key
okay found a solution on:
PHP : multidimensional array merge recursive
function array_merge_recursive_ex(array $array1, array $array2)
{
$merged = $array1;
foreach ($array2 as $key => & $value) {
if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
$merged[$key] = array_merge_recursive_ex($merged[$key], $value);
} else if (is_numeric($key)) {
if (!in_array($value, $merged)) {
$merged[] = $value;
}
} else {
$merged[$key] = $value;
}
}
return $merged;
}
and with this function i can merge that mutlidemensional array without loosing keys:
$newarray =[];
foreach($array as $firstkey){
$newarray = array_merge_recursive_ex($newarray, $firstkey);
}

Check duplicate entry into object array php laravel

Illuminate\Database\Eloquent\Collection Object
(
[items:protected] => Array
(
[0] => User Object
(
[original:protected] => Array
(
[user_id] => 123456
[active] => 1
[name] => ABC XYZ
[first_name] => ABC
[last_name] => XYZ
[email] => abc#xyz.com
[username] => abcxyz
[secret_code] => S4#$sdD
)
)
[1] => User Object
(
[original:protected] => Array
(
[user_id] => 987654
[active] => 1
[name] => CBD IHK
[first_name] => CBD
[last_name] => IHK
[email] => abc#xyz.com
[username] => seCdils
[secret_code] => S4#$sdD
)
)
)
)
Identify both object array has same secret_code return boolean if exist true else false tried array_count_values return only string and number please guide thanks
I just want to check if detect secret_code same in array give me true else false
<?php
$dupes = []; // keep track of duplicates
foreach ($users as $user1) { // iterate over all items
$dupeCount = 0; // because we iterate over the same array, we always find at least the item itself (1 dupe minimum)
foreach ($users as $user2) { // check the array again
if ($user1 === $user2) { // if they are exactly the same: http://php.net/manual/en/language.oop5.object-comparison.php
$dupeCount++;
}
if ($dupeCount > 1) { // because we always find at least 1, push only when we find more than that
array_push($dupes, $user1); // add it to the result
}
}
}
However for you comment
I just want to check if detect secret_code same in array give me true
else false
which should be in your question to begin with.
collect($users)->unique(function ($item) {
return $item['secret_code'];
});

Array reduce find the small distance and return id

I use google matrix for calculate the best distance with the multiple address.
I want display the id of a small distance
My array return by the API
$com = Array(
[0] => Array (
[id] => 12
[km] => 833 km
)
[1] => Array (
[id] => 4
[km] => 546km
)
[1] => Array (
[id] => 45
[km] => 1200km
)
)
I want display the ID of small distance ( for this exemple the id is "4")
I have tried this :
$min = array_reduce($commercant,
function ($min, $item) {
if ($item['km'] < $min['km']) {
return $item;
}
return $min;
},
array('id' => -1, 'km' => PHP_INT_MAX));
echo $min['id'];
This code doesn't work and i don't know why !
if you have an idea....
Thx
use this code
usort($com, function($a, $b) {
return $a['km'] - $b['km'];
});
echo !empty($com[0]['id']) ? $com[0]['id'] : "";
it will sort your array in desc order of distance, from this sorted array you can pick first element of array.
Hope this will help you!
With ordinary sorting, you can achieve result.
http://php.net/manual/en/function.usort.php
$x = [
['id' => 12, 'km' => '833km'],
['id' => 4, 'km' => '546km'],
['id' => 45, 'km' => '1200km']
];
function cmp_by_kms($arr1, $arr2) {
$km1 = intval($arr1['km']);
$km2 = intval($arr2['km']);
if ($km1 == $km2) { return 0; }
return ($km1<$km2) ? -1 : 1;
}
usort($x, "cmp_by_kms");
print_r($x[0]);
#=> Array
(
[id] => 4
[km] => 546km
)

Extracting values from arrays in custom fields

I'm trying to come up with a single array of all values in specific custom fields. The values themselves are also arrays. I've tried all sorts of array functions but haven't come across the right one or the right combination. Here is my code thus far:
$args = array(
'post_type' => 'match_report',
'post_status' => 'publish',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'report_home-scorers'
),
array(
'key' => 'report_away-scorers'
)
)
);
$reportscore = new WP_Query($args);
$scorersResults = array();
if ( $reportscore->have_posts() ) {
while ( $reportscore->have_posts() ) {
$reportscore->the_post();
$homescorers = get_post_meta($post->ID,'report_home-scorers',false);
$awayscorers = get_post_meta($post->ID,'report_away-scorers',false);
foreach ($homescorers as $homescorer){
array_push($scorersResults, $homescorer);
}
foreach ($awayscorers as $awayscorer){
array_push($scorersResults, $awayscorer);
}
?>
<?php } wp_reset_postdata(); //endif
}//endwhile
$scorerResults = remove_empty($scorersResults);
function remove_empty($array) {
return array_filter($array, '_remove_empty_internal');
}
function _remove_empty_internal($value) {
return !empty($value) || $value === 0;
}
Here what I get if I print_r($scorerResults); :
Array
(
[1] => Array
(
[0] => 1
[1] => 63
)
[2] => Array
(
[0] => 263
[1] => 195
)
[3] => Array
(
[0] =>
)
[4] => Array
(
[0] =>
)
)
I just want the values in the internal arrays in an array.
Assuming you want the $scoreResults array to end up as array(1,63,263,195) you could use the array_reduce function like this:
function gatherScores($lhs, $rhs) {
foreach ($rhs as $key => $value)
if ($value)
$lhs[] = $value;
return $lhs;
}
$scorerResults = array_reduce($scorerResults, "gatherScores", array());
I'm not sure what the blank values are in your third and fourth arrays and how they should be handled, so you may need to change the if ($value) condition to check for something different. As it stands it'll obviously also filter out zero scores.

Convert 3 dimension to 2 dimension

I got a query result like this : -
Array(
[0] => Array
(
[0] => Array
(
[id] => 1
[name] => Japan
)
)
[1] => Array
(
[0] => Array
(
[id] => 2
[name] => Nepal
)
)
}
How can I convert it to
Array
(
[0] => Japan
[1] => Nepal
)
The query used to get first array is 'select id , name from country;'
Please help me.
foreach ($element as $array) {
$element = $element[0]["name"];
}
Or,
function extractName($element) {
return $element[0]["name"];
}
$newArray = array_map("extractName", $array);
Extract!
$newArray = Set::extract($oldArray, '{n}.0.name');
More here.

Resources