PHP - get unique strings from array - php

I am new to this place and I have a question about PHP that I can't figure out.
What I am trying to do is create an array of strings, but that's not the problem. The problem is I have no idea how to get the only string that I need.
Example code:
$array = [];
$array[$game] = $string;
I want to keep creating strings for one single game but there will but more and more strings coming in the array from different games. I want to get only the ones from a single game, I don't know if you get what I'm talking about but I hope so because I'm frustrated that I can't figure out a way.

You have to create sub array for each game then set strings inside
// checking it sub array already not exits to not overwrite it
if( isset($array[$game]) ){
$array[$game] = array();
}
then only insert your string inside it
$array[$game][] = $string1;
$array[$game][] = $string2;
...
as result you will have
array('somegame' => array(
0 => "some game string 1",
1 => "some game string 2",
...
)
)

Your question is too simple.
You are already appending the strings to array by the key of game id.
$array = [];
$array[$game] = $string;
So, your array will look like:
array(
1 => array('string 1', 'string 2'),
2 => array('string 3', 'string 4'),
3 => array('string 5', 'string 6'),
//..... and more
)
Where keys 1, 2 and 3 are the game ids.
If you want to retrieve the keys in case of game ids 1 and 2:
$game = 1;
$gameStringsOne = $arr[$game];
$game = 2;
$gameStringsTwo = $arr[$game];

Use multi-dimensional array like
$array = [];
$array[$game] = [ $string1, $string2 ];

Read the docs Use a multi-dimentional array, push strings to an array and then assign that to another array, that way you can have multiple strings to a game
<?php
$stringArray = array("str","str2");
// if needed do array_push($stringArray,"str3","str4");
array_push($gamelist['game'], $stringArray);
?>
get an array of strings when acessing game from gamelist
read more

Related

Explode string with two different separators to create multidimensional array

I have a string:
01;Tommy;32;Coder&&02;Annie;20;Seller
I want it like this:
array (size=2)
0 =>
array (size=4)
0 => string '01' (length=2)
1 => string 'Tommy' (length=5)
2 => int 42
3 => string 'Coder' (length=5)
1 =>
array (size=4)
0 => string '02' (length=2)
1 => string 'Annie' (length=5)
2 => int 20
3 => string 'Seller' (length=6)
Hope you can help me, thank you!
Not sure if the datatypes will be matching (as I believe it's all in a string) but here's the code
$myarray = array();
foreach(explode("&&",$mystring) as $key=>$val)
{
$myarray[] = explode(";",$val);
}
The explode command takes a string and turns it into an array based on a certain 'split key' which is && in your case
but since this is a dual array, I had to pass it through a foreach and another explode to solve.
It's very simple. First you need to explode the string by && and then traverse through array exploded by &&. And explode each element of an array by ;.
Like this,
<?php
$str="01;Tommy;32;Coder&&02;Annie;20;Seller";
$array=explode("&&",$str);
foreach($array as $key=>$val){
$array[$key]=explode(";",$val);
}
print_r($array);
Demo: https://eval.in/629507
you should just have to split on '&&', then split the results by ';' to create your new two dimensional array:
// $string = '01;Tommy;32;Coder&&02;Annie;20;Seller';
// declare output
$output = [];
// create array of item strings
$itemarray = explode('&&',$string);
// loop through item strings
foreach($itemarray as $itemstring) {
// create array of item values
$subarray = explode(';',$itemstring);
// cast age to int
$subarray[2] = (int) $subarray[2]; // only useful for validation
// push subarray onto output array
$output[] = $subarray;
}
// $output = [['01','Tommy',32,'Coder'],['02','Annie',20,'Seller']];
keep in mind that since php variables are not typed, casting of strings to ints or keeping ints as strings will only last depending on how the values are used, however variable type casting can help validate data and keep the wrong kind of values out of your objects.
good luck!
There is another appropach of solving this problem. Here I used array_map() with anonymous function:
$string = '01;Tommy;32;Coder&&02;Annie;20;Seller';
$result = array_map(function($value){return explode(';',$value);}, explode('&&', $string));

php extract sub array with specific key

if i have the following array:
array(
'var1' => 123,
'var2' => 234,
'var3' => 345
);
I would like to extract specific parts of this to build a new array i.e. var1 and var3.
The result i would be looking for is:
array(
'var1' => 123,
'var3' => 345
);
The example posted is very stripped down, in reality the array has a much larger number of keys and I am looking to extract a larger number of key and also some keys may or may not be present.
Is there a built in php function to do this?
Edit:
The keys to be extracted will be hardcoded as an array in the class i..e $this->keysToExtract
$result = array_intersect_key($yourarray,array_flip(array('var1','var3')));
So, with your edit:
$result = array_intersect_key($yourarray,array_flip($this->keysToExtract));
You don't need a built in function to do this, try this :
$this->keysToExtract = array('var1', 'var3'); // The keys you wish to transfer to the new array
// For each record in your initial array
foreach ($firstArray as $key => $value)
{
// If the key (ex : 'var1') is part of the desired keys
if (in_array($key, $this->keysToExtract)
{
$finalArray[$key] = $value; // Add to the new array
}
}
var_dump($finalArray);
Note that this is most likely the most efficient way to do this.

echo value from multidimensional array

My PHP call is storing a table from mySQL with the following code.
while (mysqli_stmt_fetch($stmtMyCountTotals)) {
$stmtMyCountTotalsrow = array(
'IndividualUnitsCounted' => $IndividualUnitsCounted,
'IndividualUnitsAdjusted' => $IndividualUnitsAdjusted
);
$stmtMyCountTotalsrows[] = $stmtMyCountTotalsrow;
}
$stmtMyCountTotals->close();
I can not seem to pull a individual value from it. For Example If I want to pull a number from column 1 row 2. I know this is a basic question but I can not seem to find an answer.
This is a multidimensional array, so you would access it like so:
$row1col2 = $stmtMyCountTotalsrows[1][2]
$row2col1 = $stmtMyCountTotalsrows[2][1]
But since it is associative you would want:
$var = $stmtMyCountTotalsrows[1]['IndividualUnitsCounted'];
If you want to access it by column, then you would need to retrieve the column names first into an array:
$cols = array_keys($stmtMyCountTotalsrows[0]);
$var = $stmtMyCountTotalsrows[1][$cols[1]]
// ^ where this is the column number
There are no column numbers in your array, the second dimension is an associative array. So it should be:
$stmtMyCountTotalsrows[$row_number]['IndividualUnitsCounted']
$stmtMyCountTotalsrows[$row_number]['IndividualUnitsAdjusted']
You have an array inside another array. Or a multidimensional array. It looks like this:
Array(
0 => Array(
'IndividualUnitsCounted' => 'Something',
'IndividualUnitsAdjusted' => 'Something Else'
),
1 => Array(
'IndividualUnitsCounted' => 'Yet another something',
'IndividualUnitsAdjusted' => 'Final something'
),
...
...
)
If this array is called $stmtMyCountTotalsrows:
$stmtMyCountTotalsrows[0]['IndividualUnitsCounted'] returns "Something"
$stmtMyCountTotalsrows[0]['IndividualUnitsCounted'] returns "Something Else"
$stmtMyCountTotalsrows[1]['IndividualUnitsAdjusted'] returns "Yet another something"
$stmtMyCountTotalsrows[1]['IndividualUnitsAdjusted'] returns "Final something"
If you don't know the name of the columns beforehand, you could use current() for the first:
echo current($stmtMyCountTotalsrows[1]);
Alternatively, use array_slice():
echo current(array_slice(stmtMyCountTotalsrows, 0, 1));

Understanding the basics of multidimensional arrays

I am new to using multidimensional arrays with php, I have tried to stay away from them because they confused me, but now the time has come that I put them to good use. I have been trying to understand how they work and I am just not getting it.
What I am trying to do is populate results based on a string compare function, once I find some match to an 'item name', I would like the first slot to contain the 'item name', then I would like to increment the priority slot by 1.
So when when I'm all done populating my array, it is going to have a variety of different company names, each with their respective priority...
I am having trouble understanding how to declare and manipulate the following array:
$matches = array(
'name'=>array('somename'),
'priority'=>array($priority_level++)
);
So, in what you have, your variable $matches will point to a keyed array, the 'name' element of that array will be an indexed array with 1 entry 'somename', there will be a 'priority' entry with a value which is an indexed array with one entry = $priority_level.
I think, instead what you probably want is something like:
$matches[] = array(name => 'somename', $priority => $priority_level++);
That way, $matches is an indexed array, where each index holds a keyed array, so you could address them as:
$matches[0]['name'] and $matches[0]['priority'], which is more logical for most people.
Multi-dimensional arrays are easy. All they are is an array, where the elements are other arrays.
So, you could have 2 separate arrays:
$name = array('somename');
$priority = array(1);
Or you can have an array that has these 2 arrays as elements:
$matches = array(
'name' => array('somename'),
'priority' => array(1)
);
So, using $matches['name'] would be the same as using $name, they are both arrays, just stored differently.
echo $name[0]; //'somename';
echo $matches['name'][0]; //'somename';
So, to add another name to the $matches array, you can do this:
$matches['name'][] = 'Another Name';
$matches['priority'][] = 2;
print_r($matches); would output:
Array
(
[name] => Array
(
[0] => somename
[1] => Another Name
)
[priority] => Array
(
[0] => 1
[1] => 2
)
)
In this case, could this be also a solution with a single dimensional array?
$matches = array(
'company_1' => 0,
'company_2' => 0,
);
if (isset($matches['company_1'])) {
++$matches['company_1'];
} else {
$matches['company_1'] = 1;
}
It looks up whether the name is already in the list. If not, it sets an array_key for this value. If it finds an already existing value, it just raises the "priority".
In my opinion, an easier structure to work with would be something more like this one:
$matches = array(
array( 'name' => 'somename', 'priority' => $priority_level_for_this_match ),
array( 'name' => 'someothername', 'priority' => $priority_level_for_that_match )
)
To fill this array, start by making an empty one:
$matches = array();
Then, find all of your matches.
$match = array( 'name' => 'somename', 'priority' => $some_priority );
To add that array to your matches, just slap it on the end:
$matches[] = $match;
Once it's filled, you can easily iterate over it:
foreach($matches as $k => $v) {
// The value in this case is also an array, and can be indexed as such
echo( $v['name'] . ': ' . $v['priority'] . '<br>' );
}
You can also sort the matched arrays according to the priority:
function cmp($a, $b) {
if($a['priority'] == $b['priority'])
return 0;
return ($a['priority'] < $b['priority']) ? -1 : 1;
}
usort($matches, 'cmp');
(Sourced from this answer)
$matches['name'][0] --> 'somename'
$matches['priority'][0] ---> the incremented $priority_level value
Like David said in the comments on the question, it sounds like you're not using the right tool for the job. Try:
$priorities = array();
foreach($companies as $company) {
if (!isset($priorities[$company])) { $priorities[$company] = 0; }
$priorities[$company]++;
}
Then you can access the priorities by checking $priorities['SomeCompanyName'];.

How to find the next numeric index of an existing array?

I'm looking for a simple way to obtain the next numerical index of an array for a new element that would have been chosen by PHP as well.
Example 1:
$array = array();
$array[] = 'new index';
This would be 0 for this case.
Example 1a:
$array = array(100 => 'prefill 1');
unset($x[100]);
$x[] = 'new index';
This would be 101 for this case.
Example 2:
$array = array(-2 => 'prefill 1' );
$array[] = 'new index';
This would be 0 again for this case.
Example 3:
$array = array(-2 => 'prefill 1', 1 => 'prefill 2' );
$array[] = 'new index';
This would be 2 for this case.
I'd like now to know the next numerical key that PHP would have chosen as well for the new element in the array but w/o iterating over all the arrays values if possible.
I need this for a own array implementation via the SPL that should mimic PHP default behavior if a new element is added w/o specifying the offset.
Example 4:
$array = array(-2 => 'prefill 1', 'str-key-1' => 'prefill 2', 1 => 'prefill 3' , 'str-key-2' => 'prefill 4');
$array[] = 'new index';
This would be 2 for this case again.
Example 5:
$array = array(-2 => 'prefill-1', 'str-key-1' => 'prefill-2', 1 => 'prefill-3' , '5667 str-key-2' => 'prefill-4');
$array[] = 'new index';
This would be 2 for this case as well.
Update: I've added more examples to show some of the edge cases.
Method 1:
Use end to advance the array to the end. The get the key of that item. Finally, add 1 to it to get the index of next item. Like this:
$array [ ] = 'I';
$array [4] = 'Like';
$array [ ] = 'Turtles';
end($array);
$last = key($array);
$nextindex = $last + 1;
echo $nextindex;
This outputs:
6
This method fails in cases where last index is not greatest or a string (as pointed out in comments). So, there is this better method 2 in those cases.
Method 2:
This method works on negative and string based indexes:
You can get array_keys and do a max of it, then +1 . Like this:
$array = array(-2 => 'prefill 1', 'str-key-1' => 'prefill 2', 1 => 'prefill 3' , 'str-key-2' => 'prefill 4');
echo max(array_keys($array)) + 1;
This outputs correctly:
2
A zend hash table has an element nNextFreeElement, which contains the number you are looking for. Every time an item is added, this field is updated to be the maximum of itself and the index + 1.
ZEND_API int _zend_hash_index_update_or_next_insert(HashTable *ht, ulong h, void *pData, uint nDataSize, void **pDest, int flag ZEND_FILE_LINE_DC)
{
...
if ((long)h >= (long)ht->nNextFreeElement) {
ht->nNextFreeElement = h < LONG_MAX ? h + 1 : LONG_MAX;
}
...
}
I don't think the necessary information is exposed to PHP scripts. Consider:
<?php
$x = array(100 => 'foo');
unset($x[100]);
$x[] = 'bar';
var_dump($x);
?>
array(1) {
[101]=>
string(3) "bar"
}
There would be no way to know that 101 is the next integer given that seemingly empty array, until after adding the item.
If you are building your own array class from scratch, then you could keep track of the next index via a private member variable.
Looks to me like PHP takes the next positive number after the maximum of the index values.
If all else fails, you could simply test against a copy.
// Since PHP passes by copy, we don't even need to explicitly copy.
function get_next_key($copy) {
$copy[] = 'blah';
end($copy);
return key($copy);
}
$key = get_next_key($array);

Categories