How to use a number attached to a string in associative array - php

I have a card deck array:
$cards = array("2_of hearts" => 2, "3_of_hearts" => 3, "king_of_hearts" => 10);
And I want to echo the name of the card somewhere (example: 2_of_hearts) but also calculate something with the number attached to it, but I really can't seem to make it work. Also, I was unable to find a working answer for me.
Does anyone know how to do this?

If you use a foreach loop that provides you with the key and the value like this, you get both the 2_of hearts and the 2 as variables.
$cards = array("2_of hearts" => 2, "3_of_hearts" => 3, "king_of_hearts" => 10);
foreach ( $cards as $name => $value) {
echo $name . ' has a value of ' . $value.PHP_EOL;
$calc = $value + 5;
echo 'ADDED 5 - gives ' . $calc . PHP_EOL;
}
Result
2_of hearts has a value of 2
ADDED 5 - gives 7
3_of_hearts has a value of 3
ADDED 5 - gives 8
king_of_hearts has a value of 10
ADDED 5 - gives 15
Then you just do your calculation with the $value variable

using this syntax of foreach lets you get access to the keys of the array
$cards = array("2_of hearts" => 2, "3_of_hearts" => 3, "king_of_hearts" => 10);
foreach($cards as $key=> $value){
$key = explode("_",$key);
$cardname = $key[count($key)-1];
//echo $key[0] . " of " $cardname . "<br>";
echo $value . " of " $cardname . "<br>"; // edit after comments
}
NOTE: this is off-course if you sure your keys are always has the pattern #_of_cardname

Related

implode and show with key - php

I have an array with just a single element. The key and value looks like this:
Array ( [test] => 12342 )
Result i want is this inside an variable:
test = '12342'
I tried following:
$test = "'" . implode(" ", $metric) . "'";
print_r($test);
But this gives only gives me: '12342', i wanted the '=' after key and '' around the value (this is used for SQL later on). So the result should be test = '12342'. Does not look like implode would work here. I tried looking at http_query_builder but failed.
If this array is only ever going to contain one single item, then you don’t need to loop through the data, but you can use key and current instead:
$data = ['test' => 12342];
echo key($data) . " = '" . current($data) . "'";
key gets you the key of the “current” item, and current gets its value.
By just replying your question as it is using that unique example you would do it this way assuming there is only 1 value inside your array :
$yourArray = array('test' => '12342');
foreach($yourArray as $key => $value) {
$test = $key . " = '" . $value . "'";
}
print_r($test);
If there are multiple you would do this, as each key is unique :
$yourArray = array('test' => '12342', 'testing' => '24321');
$test = array();
foreach($yourArray as $key => $value) {
$test[$key] = $key . " = '" . $value . "'";
}
var_dump($test);

Format Array Tree with Custom ID in PHP

I have an array I need formatted into a single array. The current function I have works well aside for I can't figure out how to set a custom key for the ID. The array is used to populate a select box, so I need that ID. I spent hours messing with it and I am just lost when it comes to formatting arrays.
I need the output to use a custom key (eg. $row->id ) which would output something like:
[40 =>'Florida', 50 =>'CA', 33 => 'NY']
Right now it outputting like..
[0 =>'Florida', 1 =>'CA', 2 => 'NY']
This is my current function:
protected function createRegionList($parent_id = '0', $spacing = '')
{
$arr = [];
foreach ($this->getByParentId($parent_id) as $row) {
$arr[] = $spacing . ' ' . $row->title;
$arr = array_merge($arr, $this->createRegionList($row->id, ' ' . $spacing . '—'));
}
return $arr;
}
Any help or suggestion would be much appreciated. I have found a bunch of examples, but they are more multidimensional arrays and I need the output as a single array.
You can set array item key by specifying the key in brackets. See PHP docs.
Try this
$arr[$row->id] = $spacing . ' ' . $row->title;
array_merge is not preserving keys. Use array_replace.
Or just union these together
$arr = [];
foreach ($this->getByParentId($parent_id) as $row) {
$arr[] = $spacing . ' ' . $row->title;
$childs = $this->createRegionList($row->id, ' ' . $spacing . '—');
$arr = $childs + $arr;
}
return $arr;

Randomly select key from array to return data mapped to that key of the array

Newbie here attempting to make a simple function, I think I'm close to a solution, but I'm stuck currently with an illegal offset type.
The function will, based on the number of keys, select one of the keys randomly and then propagate my echo statement so that the desired data will then propagate the function echo statements. i.e. if key '3' is selected, the Username, first name, and last name will be populated with the data associated with the third key '[3]' of the array '$aaUser'.
I have tried searching stack overflow, php.net and googled to try to find a solution to attempt to resolve this function but as yet I have not found an answer which I can understand at this time.
my example array:
$aaUser = [ //Make multidimensional
// 0 => nameUser
// 1 => namefirst
// 2 => namelast
0 => ["monkeework", "my", "name"],
1 => ["mentor", "Portia", "Plante"],
2 => ["teacher", "Bill", "Newman"],
3 => ["friend", "Sage", "Gerky"],
4 => [ "pet", "pedro", "" //last postion left empty - if empty we skip]
];
my function:
function getRandomUser($arr){
$myKey = array_rand($arr);
$myValue = $arr[$myKey];
echo 'Username: ' . $arr[$myValue][0] . '<br />';
echo 'Name: ' . $arr[$myValue][1] . ' ' . $arr[$myValue][2] . '<br /><br />';
How I call the function:
getRandomUser($aaUser);//select array, get array data back as echo statements
You already set $myValue = $arr[$myKey]; so below where you echo the values you just need to reference $myValue[1] and not $arr[$myValue][1].
function getRandomUser($arr){
$myKey = array_rand($arr);
$myValue = $arr[$myKey];
echo 'Username: ' . $myValue[0] . '<br />';
echo 'Name: ' . $myValue[1] . ' ' . $myValue[2] . '<br /><br />';
$aaUser is passed into the function, and is now set as $arr inside the function. The first line returns a random key from $arr. The next line sets $myValue equal to the value of $arr[$myKey]. So for example.
$myKey = 3; // randomly selected key
$myValue = $arr[3] = $aaUser[3] = array("friend", "Sage", "Gerky");
$myValue = array("friend", "Sage", "Gerky"); // what $myValue holds now
$arr and $aaUser are the same. So whatever is held in $arr[3] will be set to $myValue. To access the array we just call $myValue[1].
If you try to call $arr[$myValue][1] that's like saying $arr[array("friend", "Sage", "Gerky")][1].

How can I efficiently search a field for flipped word order?

I have the following array.
$arr = array('foo','bar','foo-bar','abc','def','abc-def','ghi','abc-def-ghi');
I'm given a new string to decide to add to the array or not. If the string is already in the array, don't add it. If it is not in the array in its current form, but in a flipped word form is found, don't add it.
How should I accomplish this?
Examples:
'foo' —-> N - Do NOT add, already found
'xyz' —-> Y - Add, this is new
'bar-foo' —-> N - Do NOT add, already found in the flipped form 'foo-bar'
'ghi-jkl' —-> Y - Add, this is new
What do you recommend?
If you want to exclude items whose elements ('abc','ghi', etc.) are contained in another order and not only reversed, you could do:
$arr = array('foo','bar','foo-bar','abc','def','abc-def','ghi','abc-def-ghi');
function split_and_sort($str) {
$partsA = explode('-', $str);
sort($partsA);
return $partsA;
}
$arr_parts = array_map('split_and_sort', $arr);
$tests = array('foo','xyz','bar-foo','ghi-jkl');
$tests_parts = array_map('split_and_sort', $tests);
foreach($tests_parts as $test) {
if( !in_array($test, $arr_parts)) {
echo "adding: " . join('-', $test) . "\n";
$arr[] = join('-', $test);
}
else {
echo "skipping: " . join('-', $test) . "\n";
}
}
var_export($arr);
which outputs:
skipping: foo
adding: xyz
skipping: bar-foo
adding: ghi-jkl
array (
0 => 'foo',
1 => 'bar',
2 => 'foo-bar',
3 => 'abc',
4 => 'def',
5 => 'abc-def',
6 => 'ghi',
7 => 'abc-def-ghi',
8 => 'xyz',
9 => 'ghi-jkl',
)
Heres a suggestions on one way you can try...
for each string in $arr, reverse it as push into another array called $rev_arr
then...
$new_array = array();
foreach ($arr as $arr_1) $new_array[$arr_1] = true; // just set something
foreach ($rev_arr as $arr_2) $new_array[$arr_2] = true; // do also for reverse
now you can check what you want to do based on
if ( isset($new_arr[ $YOUR_TEST_VARIABLE_HERE ]) ) { // match found
}

Ouputting array_count_values extracting key and values

This is probably so newbie. Basically im l
$count_versions = array();
while ($row = mysql_fetch_array($result))
{
$email_build = $row1['build_info'];
$count_versions[] = $email_build;
}
Now when I use print_r I get this
Array ( [2660] => 8 [2662] => 6 [2655] => 6 [2666] => 1 )
Which is perfect, now all I want to do is to output those values like
2660 - 8 votes
2662 - 6 votes
2655 - 6 votes
2666 - 1 votes
When I try this it seems to break up the values back into a full array which undoes my array_count_values but I am stumped
I realize this foreach loop makes no sense but its as close as I can get, any ideas how I can basically print it out like print_r does it so i can put it in a table later
$i=0;
foreach ($count_versions as $version => $nums)
{
$i++;
echo "Version: " . $nums . " - " . $count_versions . "<br />";
}
It looks so easy to do it with a foreach:
$count_versions = array ( "2660" => 8, "2662" => 6, "2655" => 6, "2666" => 1 );
foreach ($count_versions as $key => $value)
echo $key.' - '.$value.' votes<br>';
echo "Version: " . $version . " - " . $nums . " votes<br />";

Categories