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 )
Related
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;
}
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']);
}
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;
});
I'm trying to build an array in Codeigniter 3, but I cant seem to structure it properly.
I have 2 tables that I basically need to combine; questions and their associated answers.
SO, basically I need a multidimensional array, each inner array is to contain the question data along with its associated answer data.
This is what I'm doing at the moment:
$question_array = array();
foreach($course_object->result() as $question){
$question_array[] = array (
'question_id' => $question->question_id,
'question' => $question->question,
);
$answer_data = $this->get_answer_data($question->question_id);
foreach($answer_data as $answer){
$question_array[]['answer'] = $answer->answer;
$question_array[]['result'] = $answer->result;
}
}
return $question_array;
But that outputs each question as an array on its own, as well as each answer, i need to combine them somehow. This is what I'm getting:
array(2) {
["question_id"]=>
string(3) "548"
["question"]=>
string(29) "Who enforces fire safety law?"
}
array(1) {
["answer"]=>
string(11) "The Manager"
}
array(1) {
["result"]=>
string(1) "0"
}
array(1) {
["answer"]=>
string(18) "The Fire Authority"
}
array(1) {
["result"]=>
string(1) "1"
}
and this is what i need:
array(2) {
["question_id"]=>
string(3) "548"
["question"]=>
string(29) "Who enforces fire safety law?"
["answer"]=>
string(11) "The Manager"
["result"]=>
string(1) "0"
["answer"]=>
string(18) "The Fire Authority"
["result"]=>
string(1) "1"
}
I've tried things like array_push but I cant seem to get it to work?
Any ideas what I can try?
The easiest way to do it is to create a new array with what you need, and append it to the $question_array, like this. You'll need a new subarray for the answers, because you can't have duplicate keys in an array.
foreach($course_object->result() as $question){
$q_array = array (
'question_id' => $question->question_id,
'question' => $question->question,
'answers' => array()
);
$answer_data = $this->get_answer_data($question->question_id);
foreach($answer_data as $answer){
$q_array['answers'][] = array(
'answer' => $answer->answer,
'result' =>$answer->result
);
}
$question_array[] = $q_array;
}
I think this should work.
$question_array = array();
$i = 0;
foreach($course_object->result() as $question){
$question_array[$i] = array (
'question_id' => $question->question_id,
'question' => $question->question,
);
$answer_data = $this->get_answer_data($question->question_id);
foreach($answer_data as $answer){
$question_array[$i]['answer'][] = $answer->answer;
$question_array[$i]['result'][] = $answer->result;
}
$i++;
}
return $question_array;
I have an array from json_decode. And i want to reformat it.
this is my array format.
["Schedule"]=>array(1) {
["Origin"]=>
string(3) "LAX"
["Destination"]=>
string(2) "CGK"
["DateMarket"]=>
array(2) {
["DepartDate"]=>
string(19) "2015-02-01T00:00:00"
["Journeys"]=>
array(6) {
[0]=>
array(6) {
[0]=>
string(2) "3210"
[1]=>
string(14) "Plane Name"
[2]=>
string(8) "20150201"
[3]=>
string(8) "20150201"
[4]=>
string(4) "0815"
[5]=>
string(4) "1524"
}
}
}
And i want change the indexed array to associative with foreach function.
And here is my PHP code
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$value->Name= $value[1];
}
But i got an error "Attempt to assign property of non-object on line xXx..
My Question is, how to insert a new associative array to indexed array like the example that i've provide.
UPDATE : I've tried this solution
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$value['Name']=$value[1];
}
But my array format still the same, no error.
In this line:
$value->Name= $value[1];
You expect $value to be both object ($value->Name) and array ($value[1]).
Change it to something like:
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$response->Schedule['DateMarket']['Journeys'][$key]['Name'] = $value[1];
}
Or even better, without foreach:
$keys = array(
0 => 'Id',
1 => 'Name',
2 => 'DateStart',
3 => 'DateEnd',
4 => 'HourStart',
5 => 'HourEnd',
);
$values = $response->Schedule['DateMarket']['Journeys'];
$response->Schedule['DateMarket']['Journeys'] = array_combine( $keys , $values );
Array_combine makes an array using keys from one input and alues from the other.
Docs: http://php.net/manual/en/function.array-combine.php
Try this:
foreach ($response->Schedule['DateMarket']['Journeys'] as $key=>$value) {
$value['Name'] = $value[1];
}
You want to create new array index, but try to create new object.
foreach ($response->Schedule['DateMarket']['Journeys'] as $key => $value) {
$value['Name'] = $value[1];
}