Hello guys, and Happy new year!
How can I add keys to this array
$my_array = array( [0] => 703683 [1] => 734972 [2] => 967385 )
So I would like to add a single key to all values example:
$copy_array = array( ['id'] => 703683 ['id'] => 734972 ['id'] => 967385 )
I tried this solution:
new_arr = [];
foreach ($my_array as $key => $value) {
// code..
$new_arr['id'] = $value ;
}
Output:
( [id] => 703683 )
You can't. An array key is identifying the element it represents. If you set 'id' to be a specific value, then you set it to be another specific value, then you override the former with the latter. Having separate values as ids is self-contradictory anyway, unless they identify different objects. If that's the case, then you can change your code to
new_arr = [];
foreach ($my_array as $key => $value) {
// code..
$new_arr[] = ['id' => $value] ;
}
or even
new_arr = [];
foreach ($my_array as $key => $value) {
// code..
$new_arr[$value] = ['id' => $value] ;
}
but the only use of such a change would be if they have other attributes, which are not included in the codes above, since your question does not provide any specific information about them if they exist at all. If everything is only an id, then you might as well leave it with numeric indexes.
Related
I know there may be sources for this out there but I'v tried everything and I'm still not getting the proper solution. That why I'm asking for you help out here.
I have a $_POST array and I want to put values in a an array. Here is the final out I want:
$response = [
['category' => 2, 'value' => "june"],
['category' => 5, 'value' => "may"],
['category' => 8, 'value' => "april"]
]
Here is the catch,the $_POST contains a value of an integer with a space in between and then a string eg '2 june', '5 may' etc
When I get this value, I split it using explode then I try to add the individual values into the response array. This is only adding just one result.
What I tried:
$response = [];
foreach ($_POST as $key => $value) {
$split = explode(" ", $value);
$result = ['category' => $split[0], 'value' => $split[1]];
$response[] = $result;
}
for some reason, the results are not as suggested above. Any ideas and suggestion will be appreciated.
Basically, problem is in the $_POST. This is global array with submitted key-values data. You should NOT use
foreach ($_POST as $key => $value) {
for parsing your data without any checks. This data is submitted by user, and not always they will have format you're waiting for.
For example, if you have a variable "dates" in your HTML form, you should be ready that $_POST['dates'] will be an array of all of your '5 june', '7 july', etc. Don't forget to check and validate all user data you received. It's important by security reason too.
Your code (foreach body, without condition) is ok, I've checked it. Try to set print_r() before explode() you will see that your're working with an array, not with a string.
Your question doesn't have an issue with processing the data into the correct resulting array. The onus falls on $_POST not holding the expected data.
All answers to this question are powerless to fix your $_POST data because no html form was supplied with your question. The only potential value that can be offered is to refine your array building process.
Here are two methods that improve your process by reducing the number of declared variables:
Demonstration uses $a=array('2 june','5 may','8 april'); to represent your $_POST array.
One-liner in a foreach loop:
foreach($a as $v){
$r[]=array_combine(["category","value"],explode(" ",$v));
}
One-liner with no loop:
$r=array_map(function($v){return array_combine(["category","value"],explode(" ",$v));},$a);
Using either process the resulting $r will be:
array (
0 =>
array (
'category' => '2',
'value' => 'june',
),
1 =>
array (
'category' => '5',
'value' => 'may',
),
2 =>
array (
'category' => '8',
'value' => 'april',
),
)
References for used functions:
explode() , array_combine() , array_map()
Try this one:
$response = [];
// just for example use this one
$data = "2 june, 5 may, 7 july";
$temp = explode(",", $data);
// and you can use this one for your case
/*$data = $_POST['var_name']; // var_name is your variable name from $_POST
$temp = explode(",", $data);*/
foreach ($temp as $key => $value) {
$split = explode(" ", trim($value));
foreach ($split as $val) {
$result = ['category' => $split[0], 'value' => $split[1]];
}
$respon[] = $result;
}
echo "<pre>";
echo print_r($respon);
echo "</pre";
the output:
Array
(
[0] => Array
(
[category] => 2
[value] => june
)
[1] => Array
(
[category] => 5
[value] => may
)
[2] => Array
(
[category] => 7
[value] => july
)
)
$response = array();
foreach ($_POST as $key => $value) {
$split = '';
$split = explode(" ", $value);
$result = array('category' => $split[0], 'value' => $split[1]);
$response[] = $result;
}
I am trying to get a specific value out of a deeply nested PHP array. I have gotten as far as reaching reaching the array that I need and storing it in a variable. The array looks like this:
Array (
[0] => Array (
[social_channel] => twitter
[link] => testing#twitter.com
)
[1] => Array (
[social_channel] => mail
[link] => hcrosby#testing.edu
)
)
Often times this array will contain numerous values such as facebook links, twitter, instagram and they will always be in different orders based on how the user inputs them. How do I only pull out the email address in this array. I know this is basic but PHP is far from my strong point.
Assuming you've got the following:
$my_array = [
['social_channel' => 'twitter', 'link' => 'testing#twitter.com'],
['social_channel' => 'mail', 'link' => 'hcrosby#testing.edu'],
];
You'd could loop over each item of the array using a foreach and then use the link array key to get the email address. For example:
foreach ($my_array as $item) {
echo $item['link']; // Or save the item to another array etc.
}
You can use array_map function
$my_array = [
['social_channel' => 'twitter', 'link' => 'testing#twitter.com'],
['social_channel' => 'mail', 'link' => 'hcrosby#testing.edu'],
];
function getMailArray($array) {
return $array['link'];
}
$result = array_map("getMailArray",$my_array);
Try this:
$arr1 = array(array('social_channel' => 'twitter', 'link' => 'testing#twitter.com'),
array('social_channel' => 'mail', 'link' => 'hcrosby#testing.edu'));
$emailArr = array();
foreach ($arr1 AS $arr) {
$emailArr[] = $arr['link'];
}
print_r($emailArr);
$assoc = [];
foreach($array as $sub){
$assoc[$sub["social_channel"]] = $assoc["link"];
}
The above changes social_channel into a key so that you can search directly like this:
$email = $assoc["email"];
Remember to ensure that the input contains the email field, just to avoid your error.log unnecessarily spammed.
<?php
function retrieveValueFromNestedList(array $nestedList, $expectedKey)
{
$result = null;
foreach($nestedList as $key => $value) {
if($key === $expectedKey) {
$result = $value;
break;
} elseif (is_array($value)){
$result = $this->retrieveValueFromNestedList($value, $expectedKey);
if($result) {
break;
}
}
}
}
$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).
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]);
}
I'm trying to add an extra class tag if an element / value is the first one found in an array. The problem is, I don't really know what the key will be...
A minified example of the array
Array (
[0] => Array(
id => 1
name = Miller
)
[1] => Array(
id => 4
name = Miller
)
[2] => Array(
id => 2
name => Smith
[3] => Array(
id => 7
name => Jones
)
[4] => Array(
id => 9
name => Smith
)
)
So, if it's the first instance of "name", then I want to add a class.
I think I sort of understand what you're trying to do. You could loop through the array and check each name. Keep the names you've already created a class for in a separate array.
for each element in this array
if is in array 'done already' then: continue
else:
create the new class
add name to the 'done already' array
Sorry for the pseudo-code, but it explains it fairly well.
Edit: here's the code for it...
$done = array();
foreach ($array as $item) {
if (in_array($item['name'], $done)) continue;
// It's the first, do something
$done[] = $item['name'];
}
I assume you're looping through this array. So, a simple condition can be used:
$first = 0;
foreach ($arr as $value) {
if (!$first++) echo "first class!";
echo $value;
// The rest of process.
}
To get just the first value of an array, you can also use the old fashioned reset() and current() functions:
reset($arr);
$first = current($arr);
Animuson has it good. There a small addition if I might:
> $done = array();
> foreach ($array as $item) {
> if (in_array($item['name'], $done)) continue;
> // It's the first, do something
> $done[] = $item['name']; }
the in_array() will get slow very fast. Try something like:
$done = array();
foreach ($array as $item) {
$key = $item['name'];
if( !isset( $done[$key] )) {
...
}
$done[$key] = true;
}
btw. Too bad this site doesn't support comments for all users.