Associative Array question

I have this array: > $items = [ > 'Mac' => [ > 'quantity' => $qty1, > 'price' => 1899.99 > ], > 'Razer Mouse' => [ > 'quantity' => $qty2, > 'price' => 79.99 > ], > 'WD HDD' => [ > 'quantity' => $qty3, > 'price' => 179.99 > ], > 'Nexus' => [ > 'quantity' => $qty4, > 'price' => 249.99 > ], > 'Drums' => [ > 'quantity' => $qty5, > 'price' => 119.99 > ] > ];

How would I specifically access the price OR quantity of Mac?

Currently I am doing:

    <?php foreach($items['Mac'] as $x => $x_value): ?>
        <p><?= $x_value ?></p>
    <?php endforeach ?>

But it is printing:

> 1 > > 1899.99

When I only want the qty1 printing which in the above example is the "1".

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/sm00mz
πŸ“…︎ Jan 15 2022
🚨︎ report
Associative Arrays: Can I assign use a regular array within an associative array?

I have a text file that I need to parse that comes from a database. Within this text file there are a few values I need to consider:

An employee number, an employee status, and an employee location.

The export may include some outdated information.

What I'm trying to accomplish is to use the $employeeNumber as the key, but the export may include multiple statuses. So I need to create logic that captures the employee number, all of the statuses, and then uses business rules to decide on the correct version of the data to store or update.

The rules are simple:

  1. If there is only one instance of the employee in the file export, we simply compare it against what's in the destination. If the imported data passes scrutiny, we commit it. If it doesn't, or the data already stored is a better fit, we keep it.
  2. If there are multiple instances in the file export (there are different reasons this may happen; this isn't relevant), we first enumerate them, and then check each of them to determine which is the best fit until we have one, and then we follow the rules in rule 1.
  3. If there is no existing data, we report that and move on to the next record to be imported.

I'm stuck on rule 2.

What I have currently is a script that reads the text file and, for each line, breaks the record into smaller pieces. It then checks to see if it's already stored in an associative record; if it's already there, it skips the record. Otherwise, it counts the number of times it's in the imported file, and then stores the employee number as the key and the total number of matches as the value.

I think the best approach is to store each found instance in an array. Take this example:

our %employee;
$employee {"123456", @values[0]} = "Test Value";
$employee {"123456", @values[1]} = "Another test value";
our $i = 0;
foreach $value (%employee { "123456", @values})
     {
     print "$i) - ".$employee{123456, @values[$i]};
     $i++;
     }

When I run this, $i increments, but it only returns "Another test value" twice. When I comment line 3 out, it returns "Test Value" twice. This suggests that my dirty trick won't work.

For my part, associative arrays are a new thing for me, so I'm learning something new and I'm trying to push it in different directions.

Is there a way to do something like this?

πŸ‘︎ 10
πŸ’¬︎
πŸ‘€︎ u/CitySeekerTron
πŸ“…︎ Nov 29 2021
🚨︎ report
Associative array in a while loop

This is my first time using php... I am building a simple crud app just to practice working with a database. But I can't figure out this while loop... the body is pretty clear but the condition is where I lose track.

<?php
    $result = $crud->get();
    while ($r = $result->fetch(PDO::FETCH_ASSOC)) { ?>
        <tr class="table-primary">
            <td><?php echo $r["attendee_id"] ?></td>
            <td><?php echo $r["attendee_firstname"] ?></td>
            <td><?php echo $r["attendee_lastname"] ?></td>
            <td><?php echo $r["attendee_date"] ?></td>
            <td><?php echo $r["attendee_email"] ?></td>
            <td><?php echo $r["attendee_phone"] ?></td>
            <td><?php echo $r["specialty_name"] ?></td>
        </tr>
<?php } ?>
πŸ‘︎ 8
πŸ’¬︎
πŸ‘€︎ u/bashhhhem66
πŸ“…︎ Dec 06 2021
🚨︎ report
Delete an element from an associative array

The below code works inside the project I wrote it for, but it may be the ugliest code I have ever written. Please help me refactor it!

So the code needs to iterate through an object with several levels, find a certain value (in the test case below, "R from acronym"), then delete that node in the object. The code also needs to adhere to the following restrictions:

  • Has to be ES5 (no ES6+)
  • Has to pass the linter, which is currently throwing a "guard-for-in" error

I tried to use delete instead of splice, but that was leaving an empty element in the array. I tried to use for of instead of for in, but that didn't like iterating over an object/associative array.

Thanks in advance for help and advice.

// Multi-level array. Sample values provided here to give an idea of the structure.
Twinkle.tag.redirectList = {
	'Grammar, punctuation, and spelling': {
		'Abbreviation': [
			{ tag: 'R from acronym', description: 'redirect from an acronym (e.g. POTUS) to its expanded form' },
			{ tag: 'R from initialism', description: 'redirect from an initialism (e.g. AGF) to its expanded form' },
			{ tag: 'R from MathSciNet abbreviation', description: 'redirect from MathSciNet publication title abbreviation to the unabbreviated title' },
			{ tag: 'R from NLM abbreviation', description: 'redirect from a NLM publication title abbreviation to the unabbreviated title' }
		],
		'Capitalisation': [
			{ tag: 'R from CamelCase', description: 'redirect from a CamelCase title' },
			{ tag: 'R from other capitalisation', description: 'redirect from a title with another method of capitalisation' },
			{ tag: 'R from miscapitalisation', description: 'redirect from a capitalisation error' }
		]
	};

// This function smells!
var deleteTag = function(tagToDelete, tagList) {
	for (var categoryKey1 in tagList) {
		for (var categoryKey2 in tagList[categoryKey1]) {
			for (var tagKey in tagList[categoryKey1][categoryKey2]) {
				if (tagList[categoryKey1][categoryKey2][tagKey]['tag'] === tagToDelete) {
					tagList[categoryKey1][categoryKey2].splice(tagKey, 1);
					return tagList;
				}
			}
		}
	}
	return tagList;
};

// Certain redirect maintenance tags shouldn't be used in certain namespaces
var isTemplateNamespace = mw.config.get('wgNamespaceNumber') === 10;
if (isTemplateNamespace) {
	Twinkle.tag.redirectList = deleteTag('R from acronym', Twinkle.tag.redirectList);
}
πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/NovemLinguae
πŸ“…︎ Nov 19 2021
🚨︎ report
Small Hacks to Sort Associative Array By Integers

Hi everyone, I just wanted to share a couple little tricks that I figured out. I'm sure these are probably old tricks to some.

  1. I was working on implementing my own sorting algorithms until I came up with a way to sort a limited range of key-value pairs with integers as the key. The problem in AHK is that Associative Arrays (or Map in v2) is sorted as strings in an ordinal fashion. That means if you put the key 2 and another key 111, the 111 will be considered as first place. Not good for sorting by integers. The solution is quite simple; use Chr(x) on your integers to turn them into a character. It may be a strange character, or maybe not even a readable one. But I tested it and it works on numbers between 0 and 1114111. Later on, if you need to use these keys, you can always use Ord(key) to get the number back. It seems like whatever algorithm and optimizations are working within associative arrays under the hood are far more efficient than implementing your own sorting algorithm in ahk, so if your keys are in numeric and in the above mentioned range, I suggest you give it a try. Unfortunately, I haven't come up with a way to handle negative numbers. Please do tell if you have come up with any other tricks to sort the associative array in different ways or different ranges of integers.
  2. I was also working on a mediocre Set class until I realized you can just use an associative array to represent a set. Just leave all of your values blank. The issue of numerical values as sets is again a problem, because concatenating 1 with 2 gives you 12, not ideal if you have another set with the actual element 12 already. To avoid confusion of which elements are in the set, I put delimiters surrounding them. For example joining the set |1| with set |2| gives you |1||2|, which now will not be ambiguous with |12|. Also, to check membership, you can just call InStr("|1||2|", "|1|"). Using a super uncommon character like Chr(1114111) will be a pretty good safety net against false positive membership checks. For example, Chr(1114111) . x . Chr(1114111) is pretty unlikely to accidentally match with anything.

It's not a whole lot, but I found these tricks to be extremely efficient, speeding up my code by thousands of times.

πŸ‘︎ 6
πŸ’¬︎
πŸ‘€︎ u/GalacticWafer
πŸ“…︎ Nov 02 2021
🚨︎ report
Append text to an element in an associative array while reading from a CSV file.

Hello gurus,

Can I ask for your help please?

I would like to append text to an element in an associative array, while reading from a CSV file.

However, I cannot seem to make it work.

The 'telephone book' CSV file contains 3 columns (number,name,company) but there will be entries with the same person name and company (e.g. Joe Bloggs) ...

101,Joe Bloggs,Bloggs Ltd
102,Sam Smith,Bloggs Ltd
103,Liz Spencer,Bloggs Ltd
104,Tom Bloggs,Bloggs Ltd
555123456,Joe Bloggs,Bloggs Ltd
555234567,Jane Bloggs,Bloggs Ltd

So, I have decided to make an associative array with the 'Name,Company' put together as the unique key in each pair: [Joe Bloggs,Bloggs Ltd]=101

If I script a simple manual routine to test the append ...

declare -A FRIENDS
FRIENDS=( [Joe Bloggs,Bloggs Ltd]=101 )
number=555123456
FRIENDS[Joe Bloggs,Bloggs Ltd]+=";$number"
declare -p FRIENDS

...it works and the extra text has been appended to the element ...

declare -A FRIENDS=(["Joe Bloggs,Bloggs Ltd"]="101;555123456" )

However, if I read a CSV file and deal with the duplicate by trying to append the 'number' it does not show in the array ...

CSVFILE=friends.csv
declare -A FRIENDS
while IFS=, read -r number name company
do
if [[ -v "FRIENDS[$name,$company]" ]] ; then
  echo "FRIENDS[$name,$company] is already set"
  FRIENDS["$name,$company"]+=";$number"
  echo "FRIENDS[$name,$company] = ${FRIENDS[$name,$company]}"
fi
FRIENDS[$name,$company]=$number
done < $CSVFILE
declare -p FRIENDS

... which outputs ...

FRIENDS[Joe Bloggs,Bloggs Ltd] is already set
FRIENDS[Joe Bloggs,Bloggs Ltd] = 101;555123456
declare -A FRIENDS=(["Joe Bloggs,Bloggs Ltd"]="555123456" ["Liz Spencer,Bloggs Ltd"]="103" ["Tom Bloggs,Bloggs Ltd"]="104" ["Sam Smith,Bloggs Ltd"]="102" ["Jane Bloggs,Bloggs Ltd"]="555234567" )

Why is the element in that array being updated and not being updated?!

What am I doing wrong?

Hope you can help.

Many thanks,

Paully

πŸ‘︎ 3
πŸ’¬︎
πŸ“…︎ Oct 25 2021
🚨︎ report
(Syntax) Question regarding the use of associative arrays within ImageSearch

In my code, I want to use associative arrays and accordingly provide ImageSearch with the right image path depending on the key.

But I'm struggling with the syntax if I don't have an intermediate step, where I declare another variable (localPath) and assign it that value first. I reckon there's a way I can do that directly, too?

imgPathes := []
imgPathes["exit"] := "exit.png"
imgPathes["button"] := "button.png"

localPath := imgPathes["exit"]
ImageSearch, foundX, foundY, 0, 0, 1200, 1200, *5 %localPath% ; works well
; I want to do this directly without an extra variable but all these don't work
ImageSearch, foundX, foundY, 0, 0, 1200, 1200, *5 %imgPathes["exit"]% ; syntax error
ImageSearch, foundX, foundY, 0, 0, 1200, 1200, *5 % imgPathes["exit"] ; syntax error 2
ImageSearch, foundX, foundY, 0, 0, 1200, 1200, *5 imgPathes[exit] ; Errorlevel 2
ImageSearch, foundX, foundY, 0, 0, 1200, 1200, *5 imgPathes["exit"] ; Errorlevel 2
MsgBox, Error Level: %ErrorLevel%
πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/NKG_and_Sons
πŸ“…︎ Sep 25 2021
🚨︎ report
For loop prints more elements than exist in associative array.

Figured it out down in the comments. Thanks for all the help!

I'm stumped. I have an associative array with IPs for keys and host names for values. Populated by running nslookup and assigning the value where result is successful.

Array is 13 in length. If I run a for loop to print values, eg ${array[@]} I get 13 lines. If I run the loop on keys, eg ${!array[@]} I get 31 lines.

Not seeing rhyme or reason to why some but not all keys are duplicated, and running a length check on the array at time of generation and at the end of the script shows 13.

What on earth could cause the for loop on keys to print duplicate lines?

#!/bin/bash
iplist=(
1.2.3.4
5.6.7.8
11.22.33.44
11.22.33.44
)
cd /working/directory
declare -A uniqueIPs
uniqueIPs[`printf "%s\n" "${iplist[@]" | sort -u`]=""

for each in ${!uniqueIPs[@]}; do
    if host=$(nslookup $each | grep -o -P '(?<=name\ \=\ ).*?(?=\.)'); then
        uniqueIPs[$each]=$host
    fi
done

for each in ${!uniqueIPs[@]}; do
    echo "Key: $each Value: ${uniqueIPs[$each]}"
done
πŸ‘︎ 10
πŸ’¬︎
πŸ‘€︎ u/ahandmadegrin
πŸ“…︎ Jul 19 2021
🚨︎ report
How do I Reorganize my output system as a function that takes a single row associative array as its input.

How do I Reorganize my output system as a function that takes a single row associative array as its input.

<?php

$cars = [

"Ford" => ["Explorer" , "2019"], "Honda" => ["Accord", "2020"] , "Dodge" => ["Ram" , "2021"] ];

foreach ($cars as $make => list($model , $year )) {

echo "The customer bought a" ." " .$make ." " .$model ." " .$year ."\n";

echo "<br>";

//print_r($cars);

}

?>

πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/lostsonsss
πŸ“…︎ Sep 01 2021
🚨︎ report
How do I make an associative array?

How do I make an associative array? I know in PHP you can doing the following:

$array = Array(
     "value" =&gt; "another value",
     "value1" =&gt; "another value 1"
);

echo $array["value1"]; // outputs another value 1

Is there a way to do this in GML?

πŸ‘︎ 8
πŸ’¬︎
πŸ‘€︎ u/Paughton
πŸ“…︎ Aug 17 2021
🚨︎ report
How can I remove the last comma after looping through an associative array? Short code included

Hi

So I have this WordPress function that gets what languages each blog post is available in.

&lt;p&gt;Blog available in: 
&lt;?php 
  $available_languages = pll_get_post_translations(get_the_ID());
  foreach($available_languages as $slug =&gt; $val) : ?&gt;
    &lt;a href="#"&gt;&lt;?= pll_get_post_language($val, 'name'); ?&gt;&lt;/a&gt;, 
  &lt;?php endforeach; ?&gt;
&lt;/p&gt;

The $available_languages outputs this:

Array
(
    [en] =&gt; 29
    [es] =&gt; 101
    [fr] =&gt; 112
    [it] =&gt; 116
)

The output of the entire code is this (the languages are hyperlinked):

Blog available in: English, Español, Français, Italiano, 

How can I make sure the very last item doesn't get the comma-space after it?

Thanks

πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/ashkanahmadi
πŸ“…︎ Aug 05 2021
🚨︎ report
Dynamically create Help-gui from the contents of three associative arrays

Hello,

I am stuck writing a help-gui - I often have problems with GUI's in general, as soon as they become even remotely complex.

I need the following:

Assume we have three Arrays:

out - associative array, contains the currently active settings of the script.

out_defaut - associative array, contains the default settings of the script. These settings are written into out if a respective key (=setting) is not set manually, to ensure all required settings are populated when the options-array is passed on to further functions

Explanations - associative array, contains hand-typed explanation strings for the different settings.

The key in all three arrays is the flag used to identify the setting within the input. Think TOC_Indent:true, with TOC_indent being the key, and true being the value in this case.

As the number of settings and respective explanations are too many to just spam a msgbox, As everything is held in arrays (because I am both smart (/s) and I believe I sometimes just want to torture myself),

I want to get a solution which is similar to the one in Lintalist's Config-window (example of image here) (google-drive img-link).

I am looking for a similarly structured and working gui, just not as many settings. Ideally, I would wrap this into a function to feed the three arrays (active options, default options, explanations) and just reuse the hell out of this.

I tried skimming through the source code for lintalist, but I'd need a few weeks to decipher where what is and understand it - and I absolutely don't have that time in the following ~weeks~ months.


Now the problem is... I have no idea where to start on such a GUI .____.

Neither how exactly it would need to function logically, nor even how I would start building it. And that's a real shame, considering I do write quite a lot of ahk code (at least quite a lot for someone who is doing this for fun and enjoyment as well. It is a hobby, even if it is tremendously helpful so far)


So, any ideas how to get such a dynamically build gui going properly are welcome.

This post is a mess, but I am under time pressure and don't have notes readied, so I won't recall the specifics later today.

Thank you,

Sincerely,

~Gw


Edit 1 27.08.2021 20:32:13:

I have been experimenting a bit with TreeView to get some parts set up - and I am stuck at an impossibly weird point. I have a ca

... keep reading on reddit ➑

πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/Gewerd_Strauss
πŸ“…︎ Aug 27 2021
🚨︎ report
Set value of PHP Associative Array

I'm parsing response cookies to an associative array but the problem I'm having is that if a key has an empty value '', it's returning the Warning: Undefined array key 1 . The code works but I want to get rid of this error. I've also tried array_fill() and array_fill_keys() to set the value of empty keys to "NULL" but it's not working.

$url = "https://www.youtube.com/";
$curlObj = curl_init();
curl_setopt($curlObj,  CURLOPT_URL,  $url);
curl_setopt($curlObj,  CURLOPT_RETURNTRANSFER,  1);
curl_setopt($curlObj,  CURLOPT_HEADER,  1);
curl_setopt($curlObj, CURLOPT_NOBODY, 1);
curl_setopt($curlObj,  CURLOPT_SSL_VERIFYPEER,  false);
$result = curl_exec($curlObj);
$h = array_filter(explode("\n", $result), 'trim');
$cookies = [];
$assocCookies = [];
if (is_array($h)) {
    foreach ($h as $d) {
        if ((!strpos($d, 'set-cookie') !== false)) {
	    $cookies = explode("; ", $d);
	}
    }
}
foreach ($cookies as $c) {
    $e = explode("=", $c);
    if (in_array(null, $e, true) === true) {
    $assocCookies[$e[0]] ?? 'none';
    } else { $assocCookies[$e[0]] = $e[1]; }
}

This returns

Warning: Undefined array key 1 in xampp\htdocs\cookie.php on line 52
Warning: Undefined array key 1 in xampp\htdocs\cookie.php on line 52
Array 
(
    [YSC] =&gt; wy0qYwLnnRc
    [Domain] =&gt; .youtube.com
    [Path] =&gt; /
    [Secure] =&gt;
    [HttpOnly] =&gt;
    [SameSite] =&gt; none 
)

What should I do? Any help would be greatful.

πŸ‘︎ 5
πŸ’¬︎
πŸ‘€︎ u/mujtabaofficial
πŸ“…︎ Aug 15 2021
🚨︎ report
Copy elements of an associative array over to another associative array with the same keys

Hello,

I am having a little bit of a problem right now.

I have the following code:

UserArr:=[]
DefaultArr:=[]
UserArr["KeyA"]:=1.2
UserArr["KeyB"]:=1.3

DefaultArr["KeyA"]:=1.0
DefaultArr["KeyB"]:=1.0
DefaultArr["KeyC"]:=0.1

and I need to end up with the following obj:

; I need to end up with the following, without knowing the keys (can one find them programmatically?)
DefaultArr["KeyA"]:=1.2
DefaultArr["KeyB"]:=1.3
DefaultArr["KeyC"]:=0.1

The problem is that I cannot know the keys myself, so I'd either need a way to copy these elements over without regarding keys, or figure out how to get the key of a value and do some ugly stuff. Not even sure if that would be possible or not. I suppose if it were to be possible to convert an associative array into a non-associative one and back, you could also do that, but who knows Β―_(ツ)_/Β― I don't even know if that is possible programmatically, without hardcoding it for all elements. It would be a pain in the ass if that were the case though.

Thank you.

Sincerely,

~Gw

πŸ‘︎ 6
πŸ’¬︎
πŸ‘€︎ u/Gewerd_Strauss
πŸ“…︎ May 20 2021
🚨︎ report
Nested Associative Arrays and Quotes

I have two associative arrays where the first array's value is the key of the second array and I'm getting a little lost on the correct way of nesting quotes in this situation. The two arrays are:

declare -A device_backup
declare -A backup_hash

In order to access the value from the second array I need to do the following:

hash="${backup_hash["${device_backup["$device"]}"}"

where the device variable is the key to the first array. This has three levels of quotes and I'm not sure if it's simply a matter of escaping them like this:

hash="${backup_hash[\"${device_backup[\"$device\"]}\"}"

or is there another recommended approach or am I stuck using temporary variables to first retrieve the value from the first array and then use that variable as the key to the second array?

πŸ‘︎ 11
πŸ’¬︎
πŸ‘€︎ u/HarryMuscle
πŸ“…︎ Jun 02 2021
🚨︎ report
Associative Arrays, what's up with the square bracket notation?

I wanted to use an associative array, followed the docs (as I understood them), and could not get them to work.

Here's what I wrote:

#NoEnv  
SendMode Input  
SetWorkingDir %A_ScriptDir%
#Include %A_ScriptDir%\utility.ahk 

word := "bike"
asArr := {dime: "road", num: 26}

F6:: 
	debug("word:" . word . "|")
	debug("asArr dime:" . asArr[dime] . "|")
	debug("asArr dime:" . asArr.dime . "|")
	SoundBeep
	Return

debug() is in utility.ahk and just prints to a text file.

Line 10 prints fine. Line 11 is what I think the docs are suggesting but doesn't print anything. Since Arrays are objects I decided to try dot notation and that turned out to work.

What's up with the square bracket notation?

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/Imosa1
πŸ“…︎ Jul 11 2021
🚨︎ report
Inserting associative array values into strings

edit: All suggestions / critiques welcome. I am new to AHK so if you know a better way of doing something please let me know. For the listed problems below I've tried following both the online resources and every variant I could think of with no luck.

Hello, thank you for your time.

I have a rather unusual problem that I solved but now have a rather simple problem that I'm stuck on.

AHK version 1.1.32.00

What my script does: I need to VNC into a linux device and change the terminal's color scheme. These devices are running a custom version of linux that is heavily stripped down and read-only, any changes are lost on restart; however we have root and can write to one specific folder. Also, all the usual AHK stuff, e.g. Send or its variants, does not work due to the UltraVNC client, and most of your core linux utils are gone too like wget or curl or make / gcc.

What we want to do is:

  • Merge a new Xresources to replace the Appearance settings of xterm (urxvt). This requires a .Xresources file and a couple bash commands. However, we want to do so in one short command or keystroke for the user. We also have to do so over an UltraVNC connection.

Some other considerations:

  • Sending a bootstrapper over FTP was considered but not used due to the amount of typing required by the user, in addition to 'volatility' of given ftp server.
  • Building a python script to iterate over a directory (e.g. a clone of ImageStore), unsquash each version, and inject the .Xresources to home dir (/tmp) is a possibility.

The solution:

  • Ultimately I settled on loading the data into the clipboard and in one keystroke and pasting it via UltraVNC's built in hotkey for host-to-guess paste of Shift+Insert to send a bash bootstrapper and wrapper that echoes out a chosen template of an .Xresources file.

  • Sending raw keystrokes is not possible as UltraVNC captures the whole keyboard, away from Windows so AHK cannot be triggered. This can be bypassed by having Windows as the active environment, loading data into the Clipboard, switching active windows, then dumping the Clipboard into the active window of the VNC'd pc.

  • We create a bash script to remove any previous .Xresources if it exists, then, it removes itself before, we use echo to dump out an .Xresources file in /tmp/config/ so that it persists, We tell xrdb where to look for the file as, its default location is the home directory and it only looks there on boot, We then spawn a new xterm to see the change

... keep reading on reddit ➑

πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/LSatyreD
πŸ“…︎ May 15 2021
🚨︎ report
Associative array not working as expected

Hello, I'm trying to make a blackjack game and wanted to have keyvalue pairs for the values of named cards. I thought an associative array would work but I'm missing something... I declare 2 arrays like this

declare -A cardVal=( [2]=2 [3]=3 [4]=4 [5]=5 [6]=6 [7]=7 [8]=8 [9]=9 [10]=10 [Jack]="hi" [King]=10 [Queen]=10 [Ace]=11 )
cardName=( 2 3 4 5 6 7 8 9 10 Jack King Queen Ace )

for some reason whenever is try to access the values of the face cards with

echo "${cardVal[Jack]}"  

for example. it always returns 11 no matter what the value I assign to that key word. Should note that the int values work fine

Im on a mac and:

❯ bash --version
GNU bash, version 5.1.8(1)-release (x86_64-apple-darwin20.3.0)
Copyright (C) 2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later &lt;http://gnu.org/licenses/gpl.html&gt;

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/FantasticEmu
πŸ“…︎ May 22 2021
🚨︎ report
Get value number X of an associative array without knowing the key/S

Hello,

I am currently adapting a certain script to work with ahk-scripts launched before I run the script, as well as any scripts not launched through it. THe original code is at the bottom. The original script

  1. loops through a directory and stores all ahk filepaths
  2. creates a gui with the scriptnames as buttons to run them
  3. upon running a script with it, a second button is activated allowing one to kill the corresponding script via the PID that got trapped when launching that script.

The problem I am trying to resolve is that it only works with scripts it has launched itself, not those launched previously/through other means. My idea was:

  1. on startup, get the pid's and names of all running scripts from the folder this script is set up for. Write the pid's to an associative array with the filename as key. Idea comes from here, using the code by geekdude and the function from lexikos to do so.
  2. activate the kill-button out of the box for those scripts
  3. On pressing the corresponding kill-button, get the PID of the respective element out of the array and perform process,close. And I am almost finished, except for the problem that... I didn't think about and have no idea how to get the value of a specific position out of an associative array, without having the filename already, which I don't have... and wouldn't know how to get either.

In my code, the lines where we need to access the pid from the array is from lines 739-175. The upper half of the loop is me messing around, the lower one (from 2nd "stringtrimleft" onwards) is og-code.

All in all, I both feel like this may be possible, and that I am in a complete dead end right now. And I might have to start over because holy fuck I don't understand my own code anymore... probably a good warning sign something's off.

I am including my last actually stable built, which sadly is also the one where nothing has yet been implemented outside of the script this is based on, which has been stripped of some unneccessary gui-functionality I don't want.

I suspect starting with the non-messed up code by me may be easier to work with if thinking about this, but idk.

This is messy, and I am kinda lost. I suspect there may be a...less janky way, but I don't know.

Thank you.

Sincerely,

~Gw

P.S. I should at least not fuck up the title, I think. Welp Β―\_(ツ)_/Β―

Edit 1: 30.04.2021 19:54]: It

... keep reading on reddit ➑

πŸ‘︎ 6
πŸ’¬︎
πŸ‘€︎ u/Gewerd_Strauss
πŸ“…︎ Apr 30 2021
🚨︎ report
assoc: Treat vectors like associative arrays docs.rs/assoc/0.1.1/assoc…
πŸ‘︎ 45
πŸ’¬︎
πŸ‘€︎ u/myli34
πŸ“…︎ Feb 28 2021
🚨︎ report
Iterate through an associative array

Hi everyone,

I'm new to AutoHotkey and trying to figure out if there is a way to iterate through an associative array on each keypress.

I have this associative array

keys := [] 
keys.push({key:"q",value:50})
keys.push({key:"w",value:55})

I know how to loop through that array using a for loop but how can I go to the next key-value pair by pressing a key?

Second question how to check which key was pressed to do a if (keypressed == A) do something?

πŸ‘︎ 4
πŸ’¬︎
πŸ‘€︎ u/Tambien42
πŸ“…︎ Feb 24 2021
🚨︎ report
Question about Associative Arrays from someone who's new to PHP

Hi,

I'm new to coding and I'm following a course subsidised by my government for people who lost their jobs due to the pandemic.

The course wants me to create a program that's supposed to ask how many friends I have, what their names are and what their dreams are, through the terminal. I feel like I've come pretty far with my limited knowledge, but it keeps printing that everyone has the same dream. I've been at this for over a day and I can't seem to figure out what I'm doing wrong. Can anyone help me?

&lt;?php

$amountfriends = (int) readline('Of how many friends do you want me to ask their dream?' . PHP_EOL);

if ($amountfriends == 0) {
    exit('Please enter a correct number');
}
$name = [];
$dream = [];
foreach (range(1, $amountfriends) as $friend) {
    $name = readline('What's your name?' . PHP_EOL);
    $dreams[$name] = [];
    foreach ($dreams as $friend); {
        $dream = readline('What's your dream?' . PHP_EOL);
    }
}
foreach ($dreams as $name =&gt; $i) {
    echo $name . " has the following dream: " . $dream . PHP_EOL;
}
?&gt;  

I've added a screenshot of the code + the output in terminal (it's in Dutch, but everything else is still the same).

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/KingKingsons
πŸ“…︎ Mar 27 2021
🚨︎ report
Associative array field of single record into string

Hi Everyone, very new to PHP so I’m sure this is a noob question. Wondering how to take the first item (and a given field) of an associative array and put the value of that cell into a variable. I’ve trying googling / stack exchange but don’t think I’m searching with the right search terms.

The scenario is that I have a SQL table of commands which I fetch, order by the recency of the command, and want to get the value of one of the fields of that most recent command.

Thanks

πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/Splodog
πŸ“…︎ Feb 13 2021
🚨︎ report
Ruby 3 getting worse? http://kokizzu.blogspot.com/2020/12/string-associative-array-and-combsort.html
πŸ‘︎ 6
πŸ’¬︎
πŸ‘€︎ u/kokizzu2
πŸ“…︎ Dec 28 2020
🚨︎ report
Alternative to associative array?

I'm trying to save objects in an array on a nodejs server and then send it to a client using socket.io. So that I don't have to update the client data each refresh, I'm trying to give every element a key with which I can update the already existing objects on the client.

It would be the easiest to store the objects in an associative array like: players[id] = blabla , but this isn't possible, since you can't send an associative array to the client or convert it to JSON. So is there any alternative data structure which behaves similar to an associative array I could use?

πŸ‘︎ 2
πŸ’¬︎
πŸ‘€︎ u/dogefromage
πŸ“…︎ Dec 13 2020
🚨︎ report
How to add row to associative array?

Hi, I am new to lua, trying to figure out how to organize tables, index them, add data.

I need to be able to access data like

Instruments
    Bass
          Receives: {2,6}
          Sends:
   Kick
          Receives:
          Sends: {5,8}

So that I can get data like Instruments["Bass"]["Receives"]

And add to the structure like

Instruments["Blah"]["Receives"] = {}

In the repl I try, for example this arbitrarily:

a = {["bass"] = {["a"]=1, ["b"]=2}}
b = {["kick"] = {["c"]=1, ["b"]=2}}

And then table.insert(a,b)

but that produces

1
    kick
          c:1
          b:2
bass:
    a:1
    b:2

So I am not quite sure how construct this sort of data. Tips?

πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/bhuether
πŸ“…︎ Dec 11 2020
🚨︎ report
Join key and values of associative arrays with different separators

Is there a way to join the keys and values of an associative array with different separators?

I have an associative array like this:declare -A arr=(key1 val1 key2 val2)And I like to expand it in such a way:key1:val1,key2:val2

I know of the j:string: parameter expansion flag but do not know how I could use it in such a way.

I tried ${(kj/:/vj:,:)arr} and ${(j/:/kj:,:v)arr} but that only results in key1,val1,key2,val2 since the second j apparently just overwrites the first one.

Is there an elegant way of doing this, without needing to loop over the keys and values etc.?

Small extra question:Is there a way to use a colon as separator but with the colon as delimiter as well for the j flag? Escaping it seems not to work:${(j:\::)arr} results in zsh: error in flags

EDIT: I found the workaround sep=":" and then ${(pj:$sep:)arr} to work, but maybe there is still a way without using the extra variable?

πŸ‘︎ 7
πŸ’¬︎
πŸ‘€︎ u/DesmondBaer
πŸ“…︎ Aug 30 2020
🚨︎ report
Associative arrays with php priyanshupatel2301.medium…
πŸ‘︎ 3
πŸ’¬︎
πŸ‘€︎ u/darkside2301
πŸ“…︎ Nov 25 2020
🚨︎ report
Fuck associative arrays, let's just use an array containing objects with key and value attributes!
πŸ‘︎ 172
πŸ’¬︎
πŸ‘€︎ u/GCHQ
πŸ“…︎ Aug 20 2018
🚨︎ report
Sets, Maps, Associative Arrays, Dictionaries, or A-Lists in elisp?

In Clojure there are literals for maps and sets, which allow you to quickly look up the presence or the association of a value within them:

(:thing {:thing "you found thing!"}) ;=&gt; "you found thing!"
(#{:not-thing} :thing) ;=&gt; nil

What are the best ways to get these two functionalities in elisp?

πŸ‘︎ 7
πŸ’¬︎
πŸ‘€︎ u/WorldsEndless
πŸ“…︎ May 07 2020
🚨︎ report
Associative arrays in ksh

Hello everyone, I've been trying to learn more about OpenBSD's ksh lately and I just noticed that I can't create an associative array using the typeset -A command because it doesn't recognize the -A option. I looked at the man page for ksh(1) and I didn't find anything related. Is there an alternative way/reason for this? Thanks.

πŸ‘︎ 10
πŸ’¬︎
πŸ‘€︎ u/TheProgrammar89
πŸ“…︎ Apr 28 2020
🚨︎ report
String into associative array

Hello I am back after a few days of attempting to achieve my last request here. I have some what progressed since but haven't got a working solution just yet.

What I'm now trying to do is turn a long string which looks like this
"var1=0&var2=0.001&var3=EF"
into an associative array with keys => values.
Like this:
Array
(
Β  Β  [var1] => 0
Β  Β  [var2] => 0.001
Β  Β  [var3] => EF
)

I have found the explode function which helped me split the lines at the "&" delimiter, though it seems when I encode this as a JSON so I can see it on an echo each is on it's own line like I want
but each array[i] is done per character. For example using the above;

array[0] = v
array[1] = a
array[2] = r

I have searched the php documentation for various functions and even tried separating the keys with the values to reassign them as assoc.arrays easier by exploding a second time using "=" as the delimiter. I need to be able to get the keys correctly associated to make sure the rest of my script (to input this data into my database) is working.

My script (example): Pastebin

The string starts out encoded in base64, as you will notice on the example.

Thanks

πŸ‘︎ 2
πŸ’¬︎
πŸ“…︎ Feb 25 2020
🚨︎ report

Please note that this site uses cookies to personalise content and adverts, to provide social media features, and to analyse web traffic. Click here for more information.