php get name of array - php

$shortcodes['video_section'] = array(
'no_preview' => true,
'params' => 'xxx',
'shortcode' => '[sc1][/sc1]',
'popup_title' => __('Video Section', THEME_NAME),
'shortcode_icon' => __('li_video')
);
$shortcodes['image_section'] = array(
'no_preview' => true,
'params' => 'yyy',
'shortcode' => '[sc2][/sc2]',
'popup_title' => __('Image Section', THEME_NAME),
'shortcode_icon' => __('li_image')
);
$shortcodes[] = $th_shortcodes;
How can I retrieve the name of each array and then access to the key and value:
for example I need to loop throught $shortcode and get the array main name: 'image_section' 'video_section'
Then to retrieve the value of some key. I know how to retrieve key and value but really don't understand how to get the name of the declared array. If i do: var_dump($value); I saw the name of the array but how to access to it?

You can use foreach
foreach($shortcodes as $key => $value) {
echo $key // echoes "vide_section" and "image_section"
foreach($value as $innerKey => $innerValue) {
echo $innerKey // echoes 'no_preview', 'params', 'shortcode', 'popup_title', 'shortcode_icon' twice
}
}
Note that $value in this case refers to arrays, you can foreach again to access the inner values.

Use the array_flip function on the array
$array = array_flip($shortcodes);

Yes you can use foreach, where it goes through each item on array, based on creation order.
foreach($shortcodes as $key => $value) {
// $key represents video_section for 1st iteration and image_section for 2nd.
//Here each are array, so you can again iterate over $value and get each item .
foreach($value as $key2 => $value2) {
//here keys are no_preview, params and so on on subsequent iterations.
}
}

There's array_keys():
$keynames = array_keys($shortcodes);
You could foreach throught it:
foreach($shortcodes as $key=>values){ echo $key; }
or flip the values with the case (though this last one I don't recommend), and than foreach through those. But array flip is best to be left alone in this case (though I nice function to keep in the back of your head).

Related

Passing an array copy to a function expecting a reference

I have a loop of the following kind:
foreach ($values as $key => $value) {
$attrs = array('NAME' => $key);
myproc ($attrs);
......
}
Where in myproc the first parameter is defined by reference:
function myproc (& attrs) { .... }
myproc adds the passed value to some structure.
The trouble with this is that at loop end, all the arrays added to the generated structure contains the same value, the last value extracted from the loop.
I tried also something like this :
foreach ($values as $key => $value) {
$attrs = array('NAME' => $key);
$copy = $attrs;
myproc ($copy);
......
}
but the result is the same. I'not allowed to modify the procedure. Any suggestions?
Based on the comment below your question, it seems that the problem is that you are passing a reference and this reference gets updated in the loop, leading to updates in the object you are generating in your function.
To avoid this, you need to unset the variable after the function call so that the link between the value in your object and the referenced variable is broken:
foreach ($values as $key => $value) {
$attrs = array('NAME' => $key);
myproc ($attrs);
// unset the variable so that newer values of it will have no effect
// on the object generated in `myproc`
unset($attrs);
......
}
Also see the manual.
<?php
foreach(['red','pink','green'] as $colour) {
$attrs = ['colour' => $colour];
if(colourToAction($attrs)) {
$results[] = $attrs;
}
}
var_export($results);
function colourToAction(&$attrs) {
$actions = ['red'=>'stop','amber'=>'wait', 'green' => 'go'];
if(isset($attrs['colour']) && isset($actions[$attrs['colour']])){
$attrs['action'] = $actions[$attrs['colour']];
return true;
}
}
Output:
array (
0 =>
array (
'colour' => 'red',
'action' => 'stop',
),
1 =>
array (
'colour' => 'green',
'action' => 'go',
),
)

PHP store multi-dimensional array's key in foreach

It's an interesting situation for getting the array key in multi-dimensional array.
I know how to get the array value by using foreach but how to get the key value and insert into database??
Here is my code:
//Array
$BookingInfo = array(
"115"=>array(
"date"=>array(
"15/12/2014"=>array(//need to get the date but not in here
array(
//need to get the date in here!!
"from"=>2,
"to"=>5,
"user"=>"Ella",
"userid"=>"b2111"
),
array(
"from"=>5,
"to"=>7,
"user"=>"Johnson",
"userid"=>"a2413"
)
),
"16/12/2014"=>array(
array(
"from"=>4,
"to"=>8,
"user"=>"Peter",
"userid"=>"g531"
)
),
"17/12/2014"=>array(
array(
"from"=>1,
"to"=>3,
"user"=>"Chris",
"userid"=>"h024"
),
array(
"from"=>3,
"to"=>6,
"user"=>"Jennifer",
"userid"=>"f314"
)
),
"20/12/2014"=>array(
array(
"from"=>1,
"to"=>5,
"user"=>"Raymond",
"username"=>"r362"
)
),
"21/12/2014"=>array(
array(
"from"=>1,
"to"=>6,
"user"=>"Amy",
"username"=>"a754"
)
),
"23/08/2014"=>array(
array(
"from"=>2,
"to"=>4,
"user"=>"Amy",
"userid"=>"m432"
)
)
)
)
);
The foreach code:
foreach($BookingInfo as $roomNumber => $value){
foreach($value as $id => $val){
foreach($val as $bookDate => $array){
foreach($array as $key => $detail){
foreach($detail as $period =>$info){
//get the $bookDate here
//if I get the "$bookDate" here, it shows the result with repeating 3 times, how can I solve it??
}
}
}
}
}
And I want to get the "15/12/2014" 2 times because of two members' booking, and the "16/12/2014" 1 times, what is the method to do it? Thanks for help.
It's probably easiest to just add the bookDate to the detail array, in the second innermost loop:
foreach($BookingInfo as $roomNumber => $value){
foreach($value as $id => $val){
foreach($val as $bookDate => $array){
foreach($array as $key => $detail){
$detail['bookDate'] = $bookDate;
foreach($detail as $detailkey =>$detailval){
print "$detailkey => $detailval\n";
}
print "***\n";
}
}
}
}
(Just make sure that whatever key you use isn't one that might be in the details array already or you might cause some confusion).
See http://codepad.org/oQT3cmo8 for output

Array ksort only shows non-like values?

Have an array for a ranking script.
Some times the key will be the same. They are numeric.
When the sort is ran, only non-like values are echoed.
Can't figure out the fix.
$list = array( $value1 => 'text', $value2 => 'text', $value3 => 'text');
krsort($list);
foreach ($list as $key => $frame) {
echo $frame;
}
If you assign two values to the same key in an array, the first value will be overridden by the second. You'll therefore end up with only one value for that key in the array.
To resolve this, I'd suggest to change your array structure like this:
<?php
$list = array( $key1 => array($key1member1, $key2member2),
$key2 => array($key2member1),
$key3 => array($key3member1, $key3member2, $key3member3) );
krsort($list);
foreach ($list as $key => $frames) {
foreach ($frames => $frame) {
echo $frame;
}
}
?>
Going by what you wrote in the comments to this question and my other answer, I'd recommend to switch keys and values.
<?php
$list = array( "frame1" => 4, "frame2" => 2, "frame3" => 99, "frame4" => 42 );
arsort($list);
foreach ($list as $frame => $ranking) {
echo $frame;
}
?>

if one array element similar to request variable, then how to fetch another elements of array

I am asking Similar question compare request values to array - it doesn't work to me, my scenario is totally different
$mkt = array(
array(
'title' => "Photos",
'iconlink' => "http://example.com/xyz.png",
'pkg' => 'test'
),
array(
'title' => "code",
'iconlink' => "http://example.com/xyz.png",
'pkg' => 'main'
),
array(
'title' => "code",
'iconlink' => "http://example.com/xyz.png",
'pkg' => 'main'
));
I am having logic issue in this problem, problem is i am getting value via $_REQUEST variable and then i compare this request value to array pkg element. If comparison is true then i want to get another elements except to matched one. In this as suggested, i am using unset to remove the key of element which is matched and all array point to new variable, it working but not for first element of array, it shows null when i compare request variable to first element of array:
$mkt = array();
$newArray = $mkt;
foreach ($newArray as $key => $value ) {
if (in_array($pn, $mkt, true)) {
unset($newArray[$key]);
}
}
$rand_ad = array_rand( $newArray, 1 );
echo json_encode( $newArray[$rand_ad] );
Please have a look on this issue very grateful to me.
Loop in each value, if $pn is equal with that loop's pkg then unset than unset that element:
$pn = 'main';
$newArray = $mkt;
foreach ($newArray as $key => $val) {
if ($pn == $val['pkg']) {
unset($newArray[$key]);
}
}
echo json_encode($newArray);
// [{"title":"Photos","iconlink":"http:\/\/example.com\/xyz.png","pkg":"test"}]

PHP array unset string

I am trying to unset a group of array keys that have the same prefix. I can't seem to get this to work.
foreach ($array as $key => $value) {
unset($array['prefix_' . $key]);
}
How can I get unset to see ['prefix_' . $key] as the actual variable? Thanks
UPDATE: The $array keys will have two keys with the same name. Just one will have the prefix and there are about 5 keys with prefixed keys:
Array {
[name] => name
[prefix_name] => other name
}
I don't want to remove [name] just [prefix_name] from the array.
This works:
$array = array(
'aa' => 'other value aa',
'prefix_aa' => 'value aa',
'bb' => 'other value bb',
'prefix_bb' => 'value bb'
);
$prefix = 'prefix_';
foreach ($array as $key => $value) {
if (substr($key, 0, strlen($prefix)) == $prefix) {
unset($array[$key]);
}
}
If you copy/paste this code at a site like http://writecodeonline.com/php/, you can see for yourself that it works.
You can't use a foreach because it's only a copy of the collection. You'd need to use a for or grab the keys separately and separate your processing from the array you want to manipulate. Something like:
foreach (array_keys($array) as $keyName){
if (strncmp($keyName,'prefix_',7) === 0){
unset($array[$keyName]);
}
}
You're also already iterating over the collection getting every key. Unless you had:
$array = array(
'foo' => 1,
'prefix_foo' => 1
);
(Where every key also has a matching key with "prefix_" in front of it) you'll run in to trouble.
I'm not sure I understand your question, but if you are trying to unset all the keys with a specific prefix, you can iterate through the array and just unset the ones that match the prefix.
Something like:
<?php
foreach ($array as $key => $value) { // loop through keys
if (preg_match('/^prefix_/', $key)) { // if the key stars with 'prefix_'
unset($array[$key]); // unset it
}
}
You're looping over the array keys already, so if you've got
$array = (
'prefix_a' => 'b',
'prefix_c' => 'd'
etc...
)
Then $keys will be prefix_a, prefix_c, etc... What you're doing is generating an entirely NEW key, which'd be prefix_prefix_a, prefix_prefix_c, etc...
Unless you're doing something more complicated, you could just replace the whole loop with
$array = array();
I believe this should work:
foreach ($array as $key => $value) {
unset($array['prefix_' . str_replace('prefix_', '', $key]);
}

Categories