I would like to add an array to within an existing array.
I am tryin to use array_push which works as long as i dont try to assign a key to the array (if i try to add a key i get a syntax error... :-()
This is my initial array:
$ResultArray = array(
"TransactionDate" => "$TransactionDate",
"tx"=>array(
"0"=>array(
"TxIndex" => "$TxIndex",
"value" => "$Value",
"PaymentConfirmedCount" => "$PaymentConfirmedCount"
),
"1"=>array(
"TxIndex" => "$TxIndex",
"value" => "$Value",
"PaymentConfirmedCount" => "$PaymentConfirmedCount"
)
)
);
i would then like to add:
$ArrayTOAdd = array(
"0"=>array(
"TxIndex" => "$TxIndex",
"value" => "$Value",
"PaymentConfirmedCount" =>
"$PaymentConfirmedCount"
)
);
if I try:
array_push($ResultArray->tx, $ArrayTOAdd);
BUT this does not work and results in a warning of "array_push() [function.array-push]: First argument should be an array"
if i try this :
array_push($ResultArray, $ArrayTOAdd);
it just adds the array but not to $ResultArray->tx
Any suggestions would be greatly welcomed!
You have to access the element in the array with $ResultArray["tx"] and not $ResultArray->tx. The second one is for the access to members in a php class. So an
array_push($ResultArray["tx"], $ArrayTOAdd);
should work.
Related
I have the following array (print_r output) -
Array ( [Ds_Date] => 08%2F06%2F2018 [Ds_Hour] => 12%3A46 [Ds_SecurePayment] => 1 [Ds_Amount] => 1000 [Ds_Currency] => 978 [Ds_Order] => 180608104552 ........
How do I set the Ds_Amount key and value to a variable to use later?
thanks
Craig.
I think you should create your array this way:
<?php
$array = array(
"Ds_Date" => "08%2F06%2F2018",
"Ds_Hour" => " 12%3A46",
"Ds_SecurePayment" => "1",
...
);
?>
And then acces it like this:
$array["Ds_Date"]
Hope it helps...
I am able to set the viewVars for a single record and mail it successfully. A problem occurs when I want to send an email containing more than one record. I find the correct records and I am able to pass them to my mail function. The problem comes in that when I debug the array passed to the mail template, I get a
Notice (8): Undefined variable: vars [APP\View\Emails\html\latest_projects.ctp, line 1]
However, just below the error, it does show me the information I want:
(int) 0 => array(
'Project' => array(
'id' => '809',
'created' => '2014-04-23',
'project_number' => 'SPN00000809',
)
),
(int) 1 => array(
'Project' => array(
'id' => '810',
'created' => '2014-04-23',
'project_number' => 'SPN00000810',
)
)
*Certain fields omitted for brevity.
How do I loop through this array in the email template? I have tried the standard foreach loop as you would in the view, but then I get the undefined variable supplied foreach problem. Any advice or suggestions?
//Pass your variable
$Email->viewVars(array('projects' => $projects));
//In your email body or template
<ul>
<?php foreach ($projects as $project) { ?>
<li><?php echo $project['Project']['project_number']; ?></li>
<?php } ?>
</ul>
like said in documentation :-
$Email->viewVars(array('value' => 12345));
you will be able to use it as $value in mail template.
just like that set your array to 'value' you will be able to use $value as array.
The problem was that the array passed, $dataForView, which is generated by cake, was a combination(?) array - meaning that some keys were associative such as $dataForView['content'] => '', while the other keys were (int)0 => array();
The array received looked as such:
array(
content => '',
(int) 0 => array(
Project => array(
fieldName1 => value,
fieldName2 => value
)
),
(int) 1 => array(
Project => array(
fieldName1 => value,
fieldName2 => value
)
)
)
I found that if I unset the associative keys (content) I am able to loop through the normalized array as per usual. I did it in this way, it might not be the best way, but it works.
//remove associative key
unset($dataForView['content']);
//loop through array and output values
foreach($dataForView as $key=>$val):
echo $val['Project']['id']; //echo other info as well
endforeach;
debug($dataForView);
Thank you all for helping.
How do I push arrays inside the "adjacencies" key value pair that should have an encapsulated array holding the "arrays" (ie. array(("nodeTo" => "$to"),("nodeTo" => "$to"))) without overwriting them and appending them similiar to "+=". also the push into the key "adjacencies" doesnt seem to pick up the value.
$node[] = array(
"adjacencies" => array(), //inside this array should go all the arrays seprated by commas.
"data" => array(
"color" => $color1,
"type" => $type1
);
// this push doesnt seem to detect the adjacencies value and doesnt really push the array inside of the container array. I also tried $node["adjacencies"][]=array("nodeTo" => "$to"); but it didnt work
$node["adjacencies"]=array("nodeTo" => "$to");
}
If you want multiple arrays within 'adjacencies', append them to the end of the array:
$node[0]['adjacencies'][] = array("nodeTo" => "$to");
Granted, you'll need to know which $node index to work with (if there are multiple nodes).
Edit:
After reading the comments, it looks like the OP's desired array structure is this:
$node = array(
'adjacencies' => array(),
'data' => array(
'color' => $color1,
'type' => $type1,
);
);
Thus, to append additional nodes to the adjacencies array, you can do this:
$node['adjacencies'][] = array('nodeTo' => "$to");
By the way you use $node in the second statement I think you meant:
$node = array(
not:
$node[] = array(
// ^^
Then you can push the array by doing:
$node['adjacencies'][] = array('nodeTo' => $to);
I have two associative arrays in PHP that are defined as following:
$this_week[] = array(
"top_song_id" => $row["view_song_id"],
"top_place" => $i,
"top_move" => "0",
"top_last" => $i,
"top_peak" => $i,
"top_rating" => get_song_rating_by_id($row["view_song_id"]),
"top_views" => $row["view_sum"],
"top_start" => $monday,
"top_end" => $sunday
);
and
$last_week[] = array(
"top_song_id" => $row["view_song_id"],
"top_place" => get_song_place_by_id($row["view_song_id"]),
"top_move" => "0",
"top_last" => get_song_last_by_id($row["view_song_id"]),
"top_peak" => get_song_peak_by_id($row["view_song_id"]),
"top_rating" => get_song_rating_by_id($row["view_song_id"]),
"top_views" => $row["view_sum"],
"top_start" => $prev_monday,
"top_end" => $prev_sunday
);
Now here is my question: how can I traverse this two arrays and perform an action if there is any song id in one array that can be found in the other one?
A for() loop doesn't work because there can be common songs for both arrays but not on the same array index.
Any help is appreciated.
An efficient way to do this is to just change the first line of the last snippet this way:
$last_week[$row["view_song_id"]] = array( // Added the song id as the array index
"top_song_id" => $row["view_song_id"],
...
After that you can use a simple for loop this way:
for ($this_week as $item) {
if ( isset ($last_week[ $item["top_song_id"] ]) ) {
// HERE YOU HAVE FOUND A DUPLICATE
}
}
if( in_array( $this_week["top_song_id"], $last_week ) ) {
//do something
}
Why not just hardcode the 5(?) comparisons you need in one if statement? No need to overcomplicate things.
I would like to retrieve the first key from this multi-dimensional array.
Array
(
[User] => Array
(
[id] => 2
[firstname] => first
[lastname] => last
[phone] => 123-1456
[email] =>
[website] =>
[group_id] => 1
[company_id] => 1
)
)
This array is stored in $this->data.
Right now I am using key($this->data) which retrieves 'User' as it should but this doesn't feel like the correct way to reach the result.
Are there any other ways to retrieve this result?
Thanks
There are other ways of doing it but nothing as quick and as short as using key(). Every other usage is for getting all keys. For example, all of these will return the first key in an array:
$keys=array_keys($this->data);
echo $keys[0]; //prints first key
foreach ($this->data as $key => $value)
{
echo $key;
break;
}
As you can see both are sloppy.
If you want a oneliner, but you want to protect yourself from accidentally getting the wrong key if the iterator is not on the first element, try this:
reset($this->data);
reset():
reset() rewinds array 's internal
pointer to the first element and
returns the value of the first array
element.
But what you're doing looks fine to me. There is a function that does exactly what you want in one line; what else could you want?
Use this (PHP 5.5+):
echo reset(array_column($this->data, 'id'));
I had a similar problem to solve and was pleased to find this post. However, the solutions provided only works for 2 levels and do not work for a multi-dimensional array with any number of levels. I needed a solution that could work for an array with any dimension and could find the first keys of each level.
After a bit of work I found a solution that may be useful to someone else and therefore I included my solution as part of this post.
Here is a sample start array:
$myArray = array(
'referrer' => array(
'week' => array(
'201901' => array(
'Internal' => array(
'page' => array(
'number' => 201,
'visits' => 5
)
),
'External' => array(
'page' => array(
'number' => 121,
'visits' => 1
)
),
),
'201902' => array(
'Social' => array(
'page' => array(
'number' => 921,
'visits' => 100
)
),
'External' => array(
'page' => array(
'number' => 88,
'visits' => 4
)
),
)
)
)
);
As this function needs to display all the fist keys whatever the dimension of the array, this suggested a recursive function and my function looks like this:
function getFirstKeys($arr){
$keys = '';
reset($arr);
$key = key($arr);
$arr1 = $arr[$key];
if (is_array($arr1)){
$keys .= $key . '|'. getFirstKeys($arr1);
} else {
$keys = $key;
}
return $keys;
}
When the function is called using the code:
$xx = getFirstKeys($myArray);
echo '<h4>Get First Keys</h4>';
echo '<li>The keys are: '.$xx.'</li>';
the output is:
Get First Keys
The keys are: referrer|week|201901|Internal|page|number
I hope this saves someone a bit of time should they encounter a similar problem.