PHP - Creating Arrays by Exploded Strings - php

I have some inputs that I need to process from a form. The # of inputs from a form depends on the number of languages in my application. For example, lets say I support english and french:
$input = array(
'name_1' => 'Some input in english',
'content_1' => 'Some long text in english',
'name_2' => 'Some input in french',
'content_2' => 'Some long text in french'
);
...Where '1' and '2' are the IDs of english and french respectively. What I want to do is explode the strings:
foreach($input as $key=>$val)
{
$exploded = explode('_', $key);
$arr = $exploded[1];
$key = $exploded[2];
}
..And then push them to separate arrays. Keep in mind that there could be 2 languages, or 10, so just initializing 2 arrays and checking for '1' or '2' as the $key won't work.
How can I push the values of each to an array so that I end up with an array that look something like this?
$results = array( '1' => array('name' => 'Some input in english', 'content' => 'Some long text in english'), '2' => array('name' => 'Some input in french', 'content' => 'Some long text in french');
Thanks in advance. One idea I had was to initialize 2 arrays based off a count of unique key values, but wanted to check first to see if there is a "right" way to do this for a function already there for something like this.

Would something like this work for you?
$results = array();
foreach($input as $key=>$val)
{
$exploded = explode('_', $key);
$results[$exploded[1]][$exploded[0]] = $val;
}

Related

Change languages in PHP echo or print

Please help me to solve this issue. I'm not sure is it possible or not! I need a small tricky solution.
<?php include_once"system/hijri_calendar.php";
echo (new hijri\datetime()) -> format ('_j');
?>
Above code gives me an output of integer (1...30) in English.
Now, After echo, I want to change this English language to other languages.
Example:
Say Above code gives me an output 1
I want to change this output (1) to other languages (১)
If I get you right you are trying to get the value from one array based on the value and key from another array. You can use array_search() to find the key from array based on value
<?php
$en = array(1,2,3,4,5,6,7,8,9,0);
$bn = array('১','২','৩','৪','৫','৬','৭','৮','৯','০');
var_dump(array_search(5, $en)); // gives the key 4 from $en where value is 5
// array keys strart with 0
// so you can do
var_dump($bn[array_search(5, $en)]); // gives ৬
PHPFiddle to play with
Quick and dirty:
function __($number, $lang)
{
if ($lang == 'en') {
return $number;
}
$translate = array();
$translate['bn'] = array(
'1' => '১',
'2' => '২',
'3' => '৩',
'4' => '৪',
'5' => '৫',
'6' => '৬',
'7' => '৭',
'8' => '৮',
'9' => '৯',
'0' => '০'
);
$translate['th'] = array(
'1' => '๑',
'2' => '๒',
'3' => '๓',
'4' => '๔',
'5' => '๕',
'6' => '๖',
'7' => '๗',
'8' => '๘',
'9' => '๙',
'0' => '๐'
);
$digits = str_split($number,1);
$return_this = '';
foreach($digits as $digit){
$return_this .= $translate[$lang][$digit];
}
return $return_this;
}
echo __('905','bn');
Break down, if the lang is en you get what you give, if bn or th, it'll break the number apart and rebuild it using the requested array.
This is basically how I do I18n except the arrays for each language are in their own files.
I've changed the arrays slightly to simplify things. If the array is in the order of the digits (so I've moved the 0 element to position 0 in the array) you can use...
$bn = array('০','১','২','৩','৪','৫','৬','৭','৮','৯');
$in = "18";
$out = "";
foreach ( str_split($in) as $ch ) {
$out .= $bn[$ch];
}
echo $out;

PHP - get unique strings from array

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

PHP - search / filter a multidimentional array by string(s)

I have a multidimensional array like this:
$testarray = array(
array(
'First name' => 'Johnny',
'Last name' => 'Milthers',
'Age' => '24'
),
array(
'First name' => 'Toby',
'Last name' => 'Thomson',
'Age' => '25'),
),
array(
'First name' => 'Jack',
'Last name' => 'Johnson',
'Age' => '25'),
);
How do i pass search strings such as 'John', to then have the array $testarray contain only the first and last array?.
I need to pass a search term, that return the whole subarray if any of the keys values contain that string.
also if i pass "Jack Johnson", $testarray should contain only the last array.
Is this possible, or am i going about it the wrong way?
how do normal search result work for databases work?
I have been looking at a lot of stack overflow pages (and PHP manual + google), but nothing helped me out, if im posting something that already has an answer, please comment me the link.
Thank you soo much!
Here's one way of doing it, bare in mind it will only work if the search arrays are nested directly in the outer search array.
function search_array($text, $array) {
return array_filter($array, function($a) use($text){
return stristr(implode(" ", $a), $text);
});
}
http://sandbox.onlinephpfunctions.com/code/09e1187ccedba0804de5d797c350e218b05951cd
I haven't tested this but this should work...
function find_in_array($search, $testarray) {
$pattern = '*'.$search.'*';
$array = array_filter($testarray, function($entry) use ($pattern) {
foreach($entry as $key=>$value) {
if (fnmatch($pattern, $value)) return true;
}
return false;
});
return $array;
}

PHP arrays - retrieving a value when other value is known

I have an array of the following structure:
$some_array = array(
array(
'font' => 'Arial',
'label' => 'Arial'
),
array(
'font' => 'PT+Sans:400',
'label' => 'PT Sans'
)
);
Let's say that I only know that one item has 'font' value of 'PT+Sans:400' and I need to retrieve the 'label' value of that single item. How can I do it easier than iterating through subarrays?
Since you are already using foreach you just want other alternatives then you can consider this solutions
Solution 1
You can try to filter your search using array_filter
$search = "PT+Sans:400" ;
$array = array_filter($array,function($v)use($search){ return $v['font'] == $search;});
var_dump($array); // returns all found array
Output
array
1 =>
array
'font' => string 'PT+Sans:400' (length=11)
'label' => string 'PT Sans' (length=7)
If you need only the label
$find = array_shift($array); // take only the first
print($find['label']); // output the label
Output
PT Sans
Solution 2
It you are not interested in return the array and all you want is just the label then you should consider array_reduce
$search = "PT+Sans:400" ;
$results = array_reduce($array,function($a,$b)use($search){ return $b['font'] == $search ? $b['label'] : null ; });
print($results);
Output
PT Sans
You need to iterate through the subarrays. Alternatively, if you have control over the data structure where this is getting stored, consider using a hash table (associative array) and then you can just check if a particular key is set.
Keep it simple:
function findLabel($source, $font)
{
foreach ($source as $item) {
if ($item['font'] == $font) {
return $label;
}
}
return null;
}
Usage:
$label = findLabel($some_array, 'PT+Sans:400');

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'];.

Categories