PHP - Push to array without key - php

I'm trying to add some $_POST values to my $_SESSION array, but I can't seem to find the best approach.
Result with array_push():
array(1) {
'product_ids' =>
array(2) {
[0] =>
string(1) "9"
[1] =>
array(1) {
[0] =>
string(2) "14"
}
}
}
expected result:
array(1) {
'product_ids' =>
array(2) {
[0] =>
string(1) "9"
[1] =>
string(2) "14"
}
}
}
Code:
if(!empty($_SESSION['product_ids'])){
array_push($_SESSION['product_ids'],$_POST['id']);
} else {
$_SESSION['product_ids'] = $_POST['id'];
}
$_POST array:
array(1) {
'id' =>
array(1) {
[0] =>
string(2) "14"
}
}
$_SESSION array:
Emtpy

If $_POST['id'] is an array of ids, it should be named $_POST['ids']. Use clear naming.
... else {
$_SESSION['product_ids'] = $_POST['id'];
Initially you're creating $_SESSION['product_ids'] as an array…
if(!empty($_SESSION['product_ids'])){
array_push($_SESSION['product_ids'],$_POST['id']);
…you're then pushing an array as value into the existing array. You want to merge those two arrays into a new array instead:
if (empty($_SESSION['product_ids'])) {
$_SESSION['product_ids'] = $_POST['ids'];
} else {
$_SESSION['product_ids'] = array_merge($_SESSION['product_ids'], $_POST['ids']);
}

Related

php get associative array in place normal array as result of function

i create function who return normal array :
function get_list_array () {
$list_object = get_list_objects();
foreach ( $list_object as $every_object) {
$list_array[] = array (
"wprm_$every_object->name" => array (
'name' => _x("$every_object->label", , 'test'),
'singular_name' => _x("$every_object->name", , 'test'),));
}
return $list_array ;
}
var_dump ($list_array);
array(2) {
[0]=> array(1) { ["object_1"]=> array(2) {
["name"]=> string(10)
"name_object1" ["singular_name"]=> string(15) "singular_name_object1" } }
[1]=> array(1) { ["object_2"]=> array(2) {
["name"]=> string(4)
"name_object2" ["singular_name"]=> string(10) "singular_name2" } } }
And i want the get in place just the associative array like this:
array ("object_1" => array (["name"]=> string(10) "name_object1"
["singular_name"]=> string(15) "singular_name_object1" } ,
"object_2" => array(2) {
["name"]=> string(4)
"name_object2" ["singular_name"]=> string(10) "singular_name2" } } }
any idea how i can modify my function in order the get the second output.
You're wrapping the array you actually want into another array by doing this:
$list_array[] = array(
"wprm_$every_object->name" => array(
Instead, you should simply assign the new array to $list_array directly:
$list_array["wprm_$every_object->name"] = array(
Also, please think about how you indent your code, because wow. Your function could look like this:
function get_list_array () {
$list_object = get_list_objects();
foreach ($list_object as $every_object) {
$list_array["wprm_$every_object->name"] = array(
'name' => _x("$every_object->label", , 'test'),
'singular_name' => _x("$every_object->name", , 'test'),
);
}
return $list_array;
}

array_column not working for an array of objects?

This is my current array structure:
array(2) {
["Ground"] => array(4) {
[0] => object(Shipping\Model\Shipping)#337 (5) {
["shipping_id"] => NULL
["min_weight"] => string(4) "0.00"
["max_weight"] => string(4) "5.00"
["shipping_method"] => string(6) "Ground"
["shipping_rate"] => string(4) "8.00"
}
[1] => object(Shipping\Model\Shipping)#385 (5) {
["shipping_id"] => NULL
["min_weight"] => string(4) "6.00"
["max_weight"] => string(5) "10.00"
["shipping_method"] => string(6) "Ground"
["shipping_rate"] => string(5) "12.00"
}
}
["Expedited"] => array(4) {
[0] => object(Shipping\Model\Shipping)#388 (5) {
["shipping_id"] => NULL
["min_weight"] => string(4) "0.00"
["max_weight"] => string(4) "5.00"
["shipping_method"] => string(9) "Expedited"
["shipping_rate"] => string(5) "12.00"
}
}
}
Every time I run array_column for max_weight I get an empty array as a result. I'm supposed to use the returned array for max().
Is there a workaround for this?
v7.0.0: Added the ability for the input parameter to be an array of objects.
Source: https://secure.php.net/manual/en/function.array-column.php
The array_column is working correctly for me in PHP 7. Here is an example ...
<?php
$shippingMethods = array("Ground" => array());
$gMethod = new stdClass();
$gMethod->shipping_id = NULL;
$gMethod->min_weight = "0.00";
$gMethod->max_weight = "5.00";
$gMethod->shipping_method = "Ground";
$gMethod->shipping_rate = "8.00";
$shippingMethods["Ground"][] = $gMethod;
$gMethod = new stdClass();
$gMethod->shipping_id = NULL;
$gMethod->min_weight = "6.00";
$gMethod->max_weight = "10.00";
$gMethod->shipping_method = "Ground";
$gMethod->shipping_rate = "12.00";
$shippingMethods["Ground"][] = $gMethod;
$shippingMethod = "Ground";
$result = max(array_column(($shippingMethods[$shippingMethod]), "max_weight"));
echo $result;
?>

Combining array values for the same associative key

I've got this array, and I want to loop through it and add up the values prices that are on the same OrderDate. The other values like the Discount code I want to add as a sub-array.
array(3) {
[0]=>
array(4) {
["OrderDate"]=>
string(10) "2018-01-01"
["DiscountCode"]=>
NULL
["TotalRevenue"]=>
string(9) "147618.76"
["Discount_Revenue"]=>
string(8) "13453.77"
}
[1]=>
array(4) {
["OrderDate"]=>
string(10) "2018-01-01"
["DiscountCode"]=>
string(6) "SALE38"
["TotalRevenue"]=>
string(8) "364.92"
["Discount_Revenue"]=>
string(8) "4083.64"
}
[2]=>
array(4) {
["OrderDate"]=>
string(10) "2018-01-01"
["DiscountCode"]=>
string(9) "WELCOME20"
["TotalRevenue"]=>
string(6) "113.83"
["Discount_Revenue"]=>
string(6) "113.83"
}
}
So it should then look like:
array(3) {
[0]=>
array(4) {
["OrderDate"]=>
string(10) "2018-01-01"
["DiscountCodes"]=> array {
[0] => "DISCOUNT"
[1] => "SALE38"
[2] => "WELCOME20"
)
["TotalRevenue"]=>
string(9) "147618.76"
["Discount_Revenue"]=>
string(8) "13453.77"
}
}
I believe I have fixed it using this loop adding to the array if the key exists. Not sure if this is the most efficient way to do it though?
foreach ($results as $k => $result){
if( array_key_exists($result['OrderDate'], $arr)){
$arr[$result['OrderDate']]['price'] += $result['TotalRevenue'];
$arr[$result['OrderDate']]['new'] = false;
} else {
$arr[$result['OrderDate']] = array(
'price' => $result['TotalRevenue'],
'new' => true
);
}
}
I've come to my own solution if anyone else needs it.
$arr = array();
foreach ($results as $k => $result){
if( array_key_exists($result['OrderDate'], $arr)){
$arr[$result['OrderDate']]['Total_Revenue'] += $result['TotalRevenue'];
$arr[$result['OrderDate']]['Discount_Revenue'] += $result['Discount_Revenue'];
isset($result['DiscountCode']) ? $arr[$result['OrderDate']]['Discount_Code'][] = $result['DiscountCode'] : '';
$arr[$result['OrderDate']]['new'] = false;
} else {
$arr[$result['OrderDate']] = array(
'Total_Revenue' => $result['TotalRevenue'],
'Discount_Revenue' => $result['Discount_Revenue'],
'new' => true
);
isset($result['DiscountCode']) ? $arr[$result['OrderDate']]['Discount_Code'][] = $result['DiscountCode'] : '';
}
}

Find object key in array using value inside an array inside the object PHP

I have an object array built like this (output of a "var_dump()" call i sanitized for the question a bit):
sObjects:array(3) {
[0]=>
object(SObject)#1 (2) {
["type"]=>
string(9) "Course__c"
["fields"]=>
array(1) {
["Id__c"]=>
string(3) "111"
}
}
[1]=>
object(SObject)#2 (2) {
["type"]=>
string(9) "Course__c"
["fields"]=>
array(1) {
["Id__c"]=>
string(3) "222"
}
}
[2]=>
object(SObject)#3 (2) {
["type"]=>
string(9) "Course__c"
["fields"]=>
array(1) {
["Id__c"]=>
string(3) "333"
}
}
}
Now, lets say i have $id = "111"
How would i go about iterating over my object array and retrieve the array key where [id__c] has a value equal to $id?
for example in this case i would expect to get back 0.
Use array_filter like this:
$array = [
[
"type" => "Course__c",
"fields" => ["Id_c" => "111"]
],
[
"type" => "Course__c",
"fields" => ["Id_c" => "222"]
]
];
$result = array_filter($array,
function($element) {
return $element['fields']['Id_c'] == "111" ? true :false;
});
print_r($result);
Will output:
Array
(
[1] => Array
(
[type] => Course__c
[fields] => Array
(
[Id_c] => 111
)
)
)
For the Sobject version, replace $element['fields']['Id_c'] with $element->fields['Id_c']
Also if you would like to pass a variable inside the callback function use:
$result = array_filter($array,
function($element) use($externalVariable){
return $element['fields']['Id_c'] == $externalVariable ? true :false;
});

Array of associative arrays, add new elements to the associative arrays [duplicate]

This question already has answers here:
How to modify an array's values by a foreach loop?
(2 answers)
Closed 4 months ago.
If I have an array like this:
array(2) {
[0]=>
array(2) {
["id"]=>
string(2) "34"
["total"]=>
string(6) "122337"
},
[1]=>
array(2) {
["id"]=>
string(2) "43"
["total"]=>
string(6) "232337"
}
}
And I want to add a new key value to each sub array, so for example, it would end like this:
array(2) {
[0]=>
array(2) {
["id"]=>
string(2) "34"
["total"]=>
string(6) "122337"
["newkey"]=>
string(6) "hihihi"
},
[1]=>
array(2) {
["id"]=>
string(2) "43"
["total"]=>
string(6) "232337"
["newkey"]=>
string(6) "hihihi"
}
}
How would I do it?
I have tried with a foreach like this:
foreach($exterior_array as $inside_array) {
$inside_array['newkey'] = "hihihi";
}
But once I get inside the foreach, the values are not saved.
foreach($exterior_array as $inside_array) {
$inside_array['newkey'] = "hihihi";
}
But once I get inside the foreach, the values are not saved.
That is because you are working on a copy of the array via $inside_array. You can access the "orignal" value you want to change by making $inside_array an alias of the origina value; using a reference:
foreach($exterior_array as &$inside_array) {
^- set the reference
$inside_array['newkey'] = "hihihi";
}
unset($inside_array);
^^^^^^^^^^^^^^^^^^^^^- remove the reference
Compare with http://php.net/foreach
foreach($exterior_array as $k=>$inside_array) {
$exterior_array[$k]['newkey'] = "hihihi";
}
try this
foreach($exterior_array as $key => $inside_array) {
$inside_array[$key]['newkey'] = "hihihi";
}
Another solution using references:
foreach($exterior_array as &$inside_array) {
$inside_array['newkey'] = "hihihi";
}
Because you are using it as a temporary array, do it like this:
foreach($exterior_array as $key => $inside_array)
{
$exterior_array[$key]['newkey'] = "hihihi";
}
Or you can do it with references as jpo suggested, this will make a new array, but keep it linked to the original (note the &):
foreach($exterior_array as &$inside_array)
{
$inside_array['newkey'] = "hihihi";
}
Try this. Tested and verified.
<?php
$parentArray = array(
array("id"=>1),
array("id"=>2),
array("id"=>3),
);
foreach($parentArray as $key=>$childArray)
{
$parentArray[$key]['newkey'] = "hello";
}
//output
Array
(
[0] => Array
(
[id] => 1
[newkey] => hello
)
[1] => Array
(
[id] => 2
[newkey] => hello
)
[2] => Array
(
[id] => 3
[newkey] => hello
)
)
?>
Its not a perfect fit for this topic, but I used this a lot in my own projects.
http://pastebin.com/TyWzLWuK
Its not very performant but easy to handle.
Example:
Fw_Recursive_Array_Helper::set($array, '0.someKey.someSubKey', 'value');
if(Fw_Recursive_Array_Helper::has($array, '0.someKey.someSubKey')) {
echo Fw_Recursive_Array_Helper::get($array, '0.someKey.someSubKey');
}
echo Fw_Recursive_Array_Helper::get($array, '1.someKey.someSubKey', 'If the key does not exist, use this');
class helper
{
public function arrayInsert($key=NULL,$value=NULL,& $array=array())
{
if(!empty($key)&&!empty($value)&&is_array($array))
{
$array[$key]=$value;
}
}
}
$obj=new helper();
$array=array('1'=>1,'a'=>'a');
$obj->arrayInsert('b','b',$array);
print_r($array)
o/p=>Array ( [1] => 1 [a] => a [b] => b )

Categories