Php array_search value of key and not a number - php

I have this array:
$lk = array(
'About_US' => array(
'en' => 'about-us',
'es' => 'sobre-nosotros',
),
'Shared_Hosting' => array(
'en' => 'website-shared-hosting',
'es' => 'alojamiento-de-sitios',
),
And I need to get the name "Shared_Hosting" by this type of search
$key = array_search('website-shared-hosting', array_column($lk, 'en'));
echo $key;
The value of $key for me shows "1" instead of "Shared_Hosting", its because we have "0" as "About_US" and "1" as "Shared_Hosting" (i believe).
If I try to echo $key this will result in "1"
I tried for all day to get $key = "Shared_Hosting"
Tried so many ways and functions!
Maybe another function instead of array_column?
Thank you everyone for read it and help!

Here's my easiest solution I could find, I don't think there would be a one-liner:
<?php
$lk = array(
'About_US' => array(
'en' => 'about-us',
'es' => 'sobre-nosotros',
),
'Shared_Hosting' => array(
'en' => 'website-shared-hosting',
'es' => 'alojamiento-de-sitios',
)
);
$foundIn = [];
forEach($lk as $key => $sub) {
if(array_search('website-shared-hosting', $sub)) {
$foundIn[] = $key;
}
}
var_dump($foundIn);
// Output: array(1) { [0]=> string(14) "Shared_Hosting" }

Related

Assign values in array based on array keys

How to modify an array based on the value as key?
array(
array(
"name" => "BIBAR",
"cutoff" => 20220725,
"totals" => 5614
),
array(
"name" => "BIBAR",
"cutoff" => 20220810,
"totals" => 5614
),
array(
"name" => "BIBAR",
"cutoff" => 20220825,
"totals" => 5614
)
);
I tried the following but it's not working:
foreach($cutoffs as $catoff) {
$ii = 0;
$sums[$ii][$catoff] = array_filter($array, function($val){
return $val['cutoff'] === $catoff ? $val['totals'] : $val;
});
$ii++;
}
My desired array:
array(
'20221025' => array(
12345,
12343,
24442
),
'20221110' => array(
3443,
744334
)
)
I'm stuck here for hours ... Please help
IF the "name" is irrelevant, I think also the previous answer should be fine.
If this code does "not work", then your explanation might be wrong, so you need to either explain better, or give us more examples - please mind that in your example the input and output are very different - the input you gave does not match your ouput.
My code is:
$a = array(
array(
"name" => "BIBAR",
"cutoff" => 20220725,
"totals" => 5614
),
array(
"name" => "BIBAR",
"cutoff" => 20220810,
"totals" => 5614
),
array(
"name" => "BIBAR",
"cutoff" => 20220725,
"totals" => 1234
)
);
print_r($a);
echo "\n================================\n\n";
$newArr = [];
foreach ($a as $k => $vArr) {
// maybe some validation would be useful here, check if they keys exist
$newArr[$vArr['cutoff']][] = $vArr['totals'];
}
print_r($newArr);
function changeArr($data){
$new = [];
foreach ($data as $v){
$new[$v['cutoff']][] = $v['totals'];
}
return $new;
}

Filter array by keys and populate new multi-dimensional array from mutated keys and original values

I need to extract data from elements with keys that start with foo. from the below array:
[
'name' => 'Bar',
'location' => 'Baz',
'foo.2021-02-01' => '50000.00',
'foo.2021-03-01' => '50000.00',
'foo.2021-04-01' => '50000.00',
'foo.2021-05-01' => '',
]
After identifying qualifying keys, I need to create a new indexed array of associative rows using the date substring from the original keys like so:
[
['date' => '2021-02-01', 'value' => '50000.00'],
['date' => '2021-03-01', 'value' => '50000.00'],
['date' => '2021-04-01', 'value' => '50000.00'],
['date' => '2021-05-01', 'value' => ''],
]
I've been able to extract the keys like so:
$keys = array_keys($theData[0]);
foreach ( $keys as $key ) {
if ( preg_match( '/foo.*/', $key ) ) {
$line = explode('.', $key);
$item[]['name'] = $line[1];
}
}
but I'm losing the values.
I then tried looping through the array manually and rebuilding the desired outcome, but the keys will change so I don't know how future-proof that would be.
Is there a wildcard approach I can take to achieve this?
You almost had it:
<?php
$theData = [
'name' => 'Bar',
'location' => 'Baz',
'foo.2021-02-01' => '50000.00',
'foo.2021-03-01' => '50000.00',
'foo.2021-04-01' => '50000.00',
'foo.2021-05-01' => ''
];
$item = [];
// No need for array_keys(), foreach() can already do this
foreach( $theData as $key => $value )
{
// check if the key starts with foo.
// Regular expressions are heavy; if you'd like then substitute with:
// if ( substr( $key, 0, 4 ) === 'foo.' )
if ( preg_match( '/^foo\\./', $key ) )
{
// foo. is 4 chars long so substring from the fourth index till the end
$item[] = [
'date' => substr( $key, 4 ),
'value' => $value
];
}
}
var_dump( $item );
Output:
array(4) {
[0]=>
array(2) {
["date"]=>
string(10) "2021-02-01"
["value"]=>
string(8) "50000.00"
}
[1]=>
array(2) {
["date"]=>
string(10) "2021-03-01"
["value"]=>
string(8) "50000.00"
}
[2]=>
array(2) {
["date"]=>
string(10) "2021-04-01"
["value"]=>
string(8) "50000.00"
}
[3]=>
array(2) {
["date"]=>
string(10) "2021-05-01"
["value"]=>
string(0) ""
}
}
A simple loop, checking for the key starting with foo. and then a little code to replace foo. in the key with nothing will do the trick
If you have PHP8 or >
$arr = [
'name' => 'Bar',
'location' => 'Baz',
'foo.2021-02-01' => '50000.00',
'foo.2021-03-01' => '50000.00',
'foo.2021-04-01' => '50000.00',
'foo.2021-05-01' => ''
];
$new = [];
foreach ($arr as $k => $v){
if ( str_starts_with( $k , 'foo.' ) ) {
$new[] = ['date' => str_replace('foo.', '', $k), 'value' => $v];
}
}
print_r($new);
RESULT
Array
(
[0] => Array
([date] => 2021-02-01, [value] => 50000.00)
[1] => Array
([date] => 2021-03-01, [value] => 50000.00)
[2] => Array
([date] => 2021-04-01, [value] => 50000.00)
[3] => Array
([date] => 2021-05-01, [value] => )
)
Alternatively, for PHP versions prior to PHP8
$new = [];
foreach ($arr as $k => $v){
if ( strpos( $k , 'foo.') !== FALSE && strpos( $k , 'foo.') == 0 ) {
$new[] = ['date' => str_replace('foo.', '', $k), 'value' => $v];
}
}
Using str_starts_with and explode
$arr = [];
foreach ($theData as $k => $v){
if (str_starts_with($k, "foo."))
$arr[] = ["date" => explode(".", $k)[1], "value" => $v];
}
var_dump($arr);
sscanf() is an ideal function to call which will both check for qualifying strings and extract the desired trailing date value. It doesn't use regex, but it does require a placeholder %s to target the date substring. If a given string doesn't qualify, no element is pushed into the result array.
Code: (Demo) (without compact())
$result = [];
foreach ($array as $key => $value) {
if (sscanf($key, 'foo.%s', $date)) {
// $result[] = ['date' => $date, 'value' => $value];
$result[] = compact(['date', 'value']);
}
}
var_export($result);
If you remove the optional technique of using compact(), this solution makes fewer function calls than all other answers on this page.
I would probably only use regex if I wanted to strengthen the validation for qualifying key strings. (Demo)
$result = [];
foreach ($array as $key => $value) {
if (preg_match('~^foo\.\K\d{4}-\d{2}-\d{2}$~', $key, $m)) {
$result[] = ['date' => $m[0], 'value' => $value];
}
}
var_export($result);

PHP - Get key from another key value through a multi dimensional array

I have the following multidimensional array that is obtained through an API.
$exchangeID = array(
0 => array(
'id' => 'vcxz',
'currency' => 'GBP',
),
1 => array(
'id' => 'mnbv',
'currency' => 'EUR',
),
2 => array(
'id' => 'lkjh',
'currency' => 'USD',
),
3 => array(
'id' => 'poiuy',
'currency' => 'KRN',
),
);
I would like to obtain the id of USD which is lkjh. I know this can be obtained by simply doing $exchangeID[2]['id']. The problem is that the array is dynamic. For example when it is loaded the first subarray may be EUR instead of GBP, and the third subarray may be KRN instead of USD.
Basically, what I have in mind is to look for the subarray where there is the currency first, then accordingly find the corresponding id. E.g. if I want to find EUR. First I find the EUR, then get 'mnbv'.
I tried this $key = array_search('USD', array_column($exchangeID, 'currency')); but I got the following error in my error_log PHP Fatal error: Call to undefined function array_column() to get at least the array number e.g. in this case 2.
You can simply filter your array, like this:
$usd_exchanges = array_filter($exchangeID, function($row) {
return $row['currency'] == "USD";
}));
var_dump($usd_exchanges[0]);
You can also return the first element of the filter, using the current method:
$usd_exchange = current(array_filter($exchangeID, function($row) {
return $row['currency'] == "USD";
})));
var_dump($usd_exchange);
Try this:
foreach ($exchangeID as $key => $arr)
if($arr['currency'] == 'USD')
echo $key;
It is possible to use following custom function to get the key:
echo getKeyRecursive('USD', $exchangeID);
function getKeyRecursive($needle, $haystack, $strict = false)
{
foreach ($haystack as $key => $item){
if(($strict ? $item === $needle : $item == $needle) || (is_array($item) && getKeyRecursive($needle, $item, $strict))) return $key;
}
return false;
}
foreach($exchangeID as $key=>$value)
{
if($exchangeID[$key]['currency']=='USD'){
$usdId=$exchangeID[$key]['id'];
break;
}
}
//echo $usdId;
//Result:ikjh
<?php
$exchangeID = array(
0 => array(
'id' => 'vcxz',
'currency' => 'GBP',
),
1 => array(
'id' => 'mnbv',
'currency' => 'EUR',
),
2 => array(
'id' => 'lkjh',
'currency' => 'USD',
),
3 => array(
'id' => 'poiuy',
'currency' => 'KRN',
),
);
$db=new PDO('sqlite::memory:','','',array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$db->query('CREATE TABLE `troll` (`dbid` TEXT, `dbcurrency` TEXT);');
$stm=$db->prepare("INSERT INTO `troll` (`dbid`,`dbcurrency`) VALUES(:id,:currency);");
array_walk($exchangeID,function($arr)use($stm){$stm->execute($arr);});
$res=$db->query("SELECT `dbid` AS `id` FROM `troll` WHERE `dbcurrency` = ".$db->quote('USD').' LIMIT 1');
$id=$res->fetch(PDO::FETCH_ASSOC);
$id=$id['id'];
var_dump($id);
see working example here http://codepad.viper-7.com/1lg2Gj
Try this if this works:
foreach($exchangeID as $key => $val)
{
if(array_key_exists('currency', $val))
if($val['currency'] == 'USD'){
echo $val['id'];
echo $val['currency'];
elseif($val['currency'] == 'GBP'){a1
echo $val['id'];
echo $val['currency']);
elseif($val['currency'] == 'EUR'){
echo $val['id'];
echo $val['currency'];
}else{
echo $val['id'];
echo $val['currency'];
}
}
}

Adding another dimension to array

I have an array of TLDs and prices, and now I want to be able to add a classification i.e. 'Australian','New Zealand','Industry' to the domains but I am having troubles adding the extra dimension.
The array I have is
$domains = array(
'.com.au' => '19.98',
'.melbourne' => '90.00',
'.academy' => '45.00',
'.accountants' => '120.00',
'.ac.nz' => '36.75');
$domains = array(
'.com.au' => array(
'country' => 'Australia',
'sector' => 'Industry',
'price' => '19.98'
),
);
Is this a beginning on what you're looking for ?
Is this code ok for you?
<?php
$domains = array(
'.com.au' => '19.98',
'.melbourne' => '90.00',
'.academy' => '45.00',
'.accountants' => '120.00',
'.ac.nz' => '36.75');
$newDomains = [];
foreach($domains as $key=>$value){
if($key == '.com.au'){
$newDomains[$key]['TLD'] = $value;
$newDomains[$key]['Industry'] = 'blabal';
}else{
$newDomains[$key] = $value;
}
}
echo '<pre>';
var_dump($newDomains);
echo '</pre>';
?>
Or even:
$domains = array(
'.com.au' => '19.98',
'.melbourne' => '90.00',
'.academy' => '45.00',
'.accountants' => '120.00',
'.ac.nz' => '36.75');
$industryArray = array(
'.com.au' => 'blabla'
);
$newDomains = [];
foreach($domains as $key=>$value){
if(isset($industryArray[$key])){
$newDomains[$key]['TLD'] = $value;
$newDomains[$key]['Industry'] = $industryArray[$key];
}else{
$newDomains[$key] = $value;
}
}
echo '<pre>';
var_dump($newDomains);
echo '</pre>';
The result is:
array(5) {
[".com.au"]=>
array(2) {
["TLD"]=>
string(5) "19.98"
["Industry"]=>
string(6) "blabla"
}
[".melbourne"]=>
string(5) "90.00"
[".academy"]=>
string(5) "45.00"
[".accountants"]=>
string(6) "120.00"
[".ac.nz"]=>
string(5) "36.75"
}

Not getting array all values using php

I have this following array
$question = array(
"ques_15" => array(
"name" => array(
"0" => "aaa"
)
),
"ques_16" => array(
"name" => array(
"0" => "bbb",
"1" => "ccc"
)
)
);
$i=0;
foreach($question as $k=>$v)
{
echo $question[$k]['name'][$i];
$i++;
}
But my output is only
aaaccc
I am missing the value bbb
You need to iterate the inner 'name' arrays - you could use a nested foreach loop:
$question = array(
"ques_15" => array(
"name" => array(
"0" => "aaa"
)
),
"ques_16" => array(
"name" => array(
"0" => "bbb",
"1" => "ccc"
)
)
);
foreach($question as $quest)
{
foreach($quest['name'] as $val)
{
echo $val;
}
}
you should loop though like so
foreach($question as $q)
{
foreach($q['name'] as $v)
{
echo $v;
}
}
in foreach you don't need a counter $i, it's for while() or for()
you array is two dimensional so you need 2 foreach
Check it out in a functional way.
The shorthand array declaration works only on PHP 5.4+ though, but it still works with your longhand array declaration.
$questions = [
'ques_15' => ['name' => ['aaa']],
'ques_16' => ['name' => ['bbb', 'ccc']]
];
array_map(function($a){
foreach ($a['name'] as $v) echo $v;
}, $questions);

Categories