If value between array key - php

Example i have this array:
$ar = array(
"1.00" => array("value0"," very bad"),
"1.49" => array("value1","bad"),
"2.00" => array("value2","not bad"),
"2.49" => array("value3","normal"),
"3.00" => array("value4","good"),
"3.49" => array("value5","very good")
);
I want to check if $val is under 1.00 the $result is array("value0"," very bad"). if between range 1.00 - 1,49 the result is array("value1","bad"), etc.
Anyone can help me?

Here is a hint :
<?php
$ar = array(
"1.00" => array("value0"," very bad"),
"1.49" => array("value1","bad"),
"2.00" => array("value2","not bad"),
"2.49" => array("value3","normal"),
"3.00" => array("value4","good"),
"3.49" => array("value5","very good")
);
$input = 1.2;
foreach($ar as $key=>$text)
{
if($input < floatval($key))
{
echo $text[0].' => '.$text[1];
break;
}
}
?>

$val = '2.15';
$val_data = ['value2','not bad'];
$data = array(
"1.00" => array("value0"," very bad"),
"1.49" => array("value1","bad"),
"2.00" => array("value2","not bad"),
"2.49" => array("value3","normal"),
"3.00" => array("value4","good"),
"3.49" => array("value5","very good")
);
$_fkey = array_keys($data)[0];
foreach($data as $key => $value){
if($key > $_fkey && $key < $val){$_fkey = $key;}
}
echo "$val, $val_data\n";
echo "=> $f_key, " . $data[$f_key] . "\n";

Related

Combine multidimentional array and ignore the array inside

I have a multidimentional array below in php.
$resultdata[0] = array(
"daynumber" => 15,
"dayname" =>'Tue',
"infomation" => array('baller', 'ROller')
);
$resultdata[1] = array(
"daynumber" => 15,
"dayname" =>'Tue',
"infomation" => array('nomal', 'Goildt')
);
$resultdata[2] = array(
"daynumber" => 24,
"dayname" =>'Thur',
"infomation" => array('Volley', 'Foller')
);
I want to combine the similar dates to form the following result.
$resultdata[0] = array(
"daynumber" => 15,
"dayname" =>'Tue',
"infomation" => array('baller', 'ROller'), array('nomal', 'Goildt')
);
$resultdata[1] = array(
"daynumber" => 24,
"dayname" =>'Thur',
"infomation" => array('Volley', 'Foller')
);
Thanx in advance
I tried using this code but it requies me to convert array to string which i dont want
function combineAndIgnore($result_arr){
$arr = array();
foreach($result_arr as $val){
$item = $val[$key];
foreach($val as $k=>$v){
$arr[$item][$k][] = $v;
}
}
// Combine unique entries into a single array
// and non-unique entries into a single element
foreach($arr as $key=>$val){
foreach($val as $k=>$v){
$field = array_unique($v);
if(count($field) == 1){
$field = array_values($field);
$field = $field[0];
$arr[$key][$k] = $field;
} else {
$arr[$key][$k] = $field;
}
}
}
return $arr;
}
I gave in to the convert to sting option which has worked anyway
<?php
$resultdata[0] = array(
"daynumber" => 15,
"dayname" =>'Tue',
"infomation" => array('baller', 'ROller','','gtk')
);
$resultdata[1] = array(
"daynumber" => 15,
"dayname" =>'Tue',
"infomation" => array('nomal', 'Goildt')
);
$resultdata[2] = array(
"daynumber" => 24,
"dayname" =>'Thur',
"infomation" => array('goon' => 'Volley', 'Foller')
);
$counter = 0;
foreach($resultdata as $veliu){
$newinfo = implode(':*:', $veliu["infomation"]);
$veliu["infomation"] = $newinfo;
$temporryry[$counter] = $veliu;
$counter++;
}
function multiarray_merge($result_arr, $key){
foreach($result_arr as $val){
$item = $val[$key];
foreach($val as $k=>$v){
$arr[$item][$k][] = $v;
}
}
// Combine unique entries into a single array
// and non-unique entries into a single element
foreach($arr as $key=>$val){
foreach($val as $k=>$v){
$field = array_unique($v);
if(count($field) == 1){
$field = array_values($field);
$field = $field[0];
$arr[$key][$k] = $field;
} else {
$arr[$key][$k] = $field;
}
}
}
return $arr;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://fonts.googleapis.com/css?family=Varela+Round" rel="stylesheet">
<style type="text/stylesheet">
font-family: 'Varela Round', sans-serif;
</style>
</head>
<body>
<pre>
<?php
$newarray = multiarray_merge($temporryry, 'daynumber');
$count = 0;
$counte = 0;
foreach($newarray as $vel){
$notin = $vel["infomation"];
if(is_array($notin)){
foreach($notin as $jin){
$reve = explode(":*:", $jin);
$good[$counte] = $reve;
$counte++;
}
}else{
$reve = explode(":*:", $notin);
$good= $reve;
}
$vel["infomation"] = $good;
$finalsolution[$count] = $vel;
$count++;
}
print_r($finalsolution);
?>
</pre>
</body>
</html>
RESULT
Array
(
[0] => Array
(
[daynumber] => 15
[dayname] => Tue
[infomation] => Array
(
[0] => Array
(
[0] => baller
[1] => ROller
[2] =>
[3] => gtk
)
[1] => Array
(
[0] => nomal
[1] => Goildt
)
)
)
[1] => Array
(
[daynumber] => 24
[dayname] => Thur
[infomation] => Array
(
[0] => Volley
[1] => Foller
)
)
)
Here's a quick-and-dirty solution to your unique use-case which you may as well Quick-T3st here:
<?php
$strJson = '[
{
"daynumber" :15,
"dayname" :"Tue",
"infomation" :["baller","ROller"]
},
{
"daynumber" :15,
"dayname" :"Tue",
"infomation" :["nomal","Goildt"]
},
{
"daynumber" :24,
"dayname" :"Thur",
"infomation" :["Volley","Foller"]
}
]';
function arrayBlend($jsonData){
$resultData = json_decode($jsonData, true);
$arrAll = [];
foreach($resultData as $data){
if(is_array($data)){
$arrAll[] = $data;
}
}
foreach($arrAll as $iCount=>&$arr){
$dayNum = $arr['daynumber'];
$dayName = $arr['dayname'];
$prev = ($iCount>0) ? $arrAll[$iCount-1] : null;
if($prev['daynumber'] == $dayNum && $prev['dayname'] == $dayName){
$arr['infomation'] = [ $prev['infomation'], $arr['infomation']];
unset($arrAll[$iCount-1]);
}
}
return $arrAll;
}
var_dump( arrayBlend($strJson) );
The var_dump() above yieds:
array:2 [
1 => array:3 [
"daynumber" => 15
"dayname" => "Tue"
"infomation" => array:2 [
0 => array:2 [
0 => "baller"
1 => "ROller"
]
1 => array:2 [
0 => "nomal"
1 => "Goildt"
]
]
]
2 => array:3 [
"daynumber" => 24
"dayname" => "Thur"
"infomation" => array:2 [
0 => "Volley"
1 => "Foller"
]
]
]

PHP Find string position in array

I have an array like this
array:32 [▼
"ID" => "7917"
"ProvinceCode" => "MB"
"Create" => "2016-05-18 18:16:26.790"
"DayOfTheWeek" => "4"
"Giai1" => "28192"
"Giai2" => "83509"
"Giai3" => "51911-02858"
"Giai4" => "14102-97270-96025-08465-89047-45904"
"Giai5" => "7892-9140-4069-8499"
"Giai6" => "6117-7471-5541-9119-4855-0566"
"Giai7" => "843-860-023"
"Giai8" => "71-13-55-89"
"Giai9" => ""
"Status" => "1"
]
I have a int variable $position = 59, and my job is find value by counting characters from Giai1 to Giai9 for 59 times and get value of this position not include character -, so I've been wrote this code
$position = 59;
$count = 0;
foreach ($data['result'][0] as $key => $item)
{
if(preg_match('#Giai#s', $key))
{
$_item = str_replace('-', '', $item);
$count = $count + strlen($_item);
$chars = str_split($item);
$chars_sp = array_count_values($chars);
$countChar = count($chars);
if($count > $position)
{
//this block contains needed position
$math = $count - $position;
$secmath = strlen($_item) - $math;
for($i=$secmath;$i>=0;$i--){
if($chars[$i] == '-'){
$splash_last++;
}
}
$secmath = $secmath + $splash_last;
if($chars[$secmath] == '-'){
echo "+1 - ";
$secmath = $secmath + 1;
}
echo "Count: $count Match: $math Secmatch: $secmath Splash_last: $splash_last";
$chars[$secmath] = 'x' . $chars[$secmath] . 'y';
$edited = implode('', $chars);
$data['result'][0][$key] = $edited;
break;
}
}
}
dd($data['result'][0]);
}
from 1 to 50 it works fine, but after position 50, the value of position I get is always wrong.
Any idea?
This should work :
$array = ["ID" => "7917",
"ProvinceCode" => "MB",
"Create" => "2016-05-18 18:16:26.790",
"DayOfTheWeek" => "4",
"Giai1" => "28192",
"Giai2" => "83509",
"Giai3" => "51911-02858",
"Giai4" => "14102-97270-96025-08465-89047-45904",
"Giai5" => "7892-9140-4069-8499",
"Giai6" => "6117-7471-5541-9119-4855-0566",
"Giai7" => "843-860-023",
"Giai8" => "71-13-55-89",
"Giai9" => "",
"Status" => "1"];
$position = 29;
$str = '';
foreach ($array as $key => $value) {
if(preg_match('#Giai#s', $key)) {
$str .= str_replace('-', '', $value);
}
}
echo $str[$position + 1];
You can do something like this:
$array = [
"ID" => "7917",
"ProvinceCode" => "MB",
"Create" => "2016-05-18 18:16:26.790",
"DayOfTheWeek" => "4",
"Giai1" => "28192",
"Giai2" => "83509",
"Giai3" => "51911-02858",
"Giai4" => "14102-97270-96025-08465-89047-45904",
"Giai5" => "7892-9140-4069-8499",
"Giai6" => "6117-7471-5541-9119-4855-0566",
"Giai7" => "843-860-023",
"Giai8" => "71-13-55-89",
"Giai9" => "",
"Status" => "1"
];
$position = 59;
$giai = array_reduce(
array_filter(
$array,
function ($key) {
return preg_match('/Giai/', $key);
},
ARRAY_FILTER_USE_KEY
),
function ($giai, $elem) {
return $giai . str_replace('-', '', $elem);
},
''
);
if ($position <= strlen($giai)) {
echo $giai[$position - 1];
}
This is more "functional approach". Firstly you filter array to get array only containing Giai* keys (be aware that this will work only in PHP >= 5.6). You can read more about array_filter(). Then you reduce this array to one string with array_reduce(). Next check if the position is valid and return the character if it is.
Here is demo.

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"
}

merge two associative arrays add titles

I have two arrays
$Array_1 = array(
'ID_1' => 'Michael',
'ID_2' => 'Jerry',
'ID_3' => 'Tony',
'ID_4' => 'Roger',
);
$Array_2 = array(
'ID_1' => 'Chef',
'ID_2' => 'Mechanic',
'ID_3' => 'Cook',
'ID_4' => 'Dealer',
);
I wish to merge them on the ID column and have my final array be in this form
$employees = array(
array(
'name' => 'Jason',
'occupation' => 'Chef'
),
array(
'name' => 'Mike',
'occupation' => 'Mechanic'
),
...
);
I know I can array combine them like below:
$new_array = array_combine(array_values($Array_1), array_values($Array_2));
but how would I add the titles "Name": and "Occupation":
Can you try this,
$Employees = array();
foreach($Array_1 as $key=>$value):
$Employees['Employees'][] = array('Name'=>$value, 'Occupation'=>$Array_2[$key]);
endforeach;
echo "<pre>";
print_r($Employees);
echo "</pre>";
echo json_encode($Employees);
OP:
{"Employees":[{"Name":"Jason","Occupation":"Chef"}, {"Name":"Mike","Occupation":"Mechanic"}]}
i dont know how the array look. but you can try my two solution
First solution
$array1 = array("id" => array("id1", "id2", "id3"), "names" => array("name1", "name2", "name3"));
$array2 = array("id" => array("id1", "id2", "id3"), "occupation" => array("occupation1", "occupation2", "occupation3"));
$filter_array = array("employees" => array());
foreach ($array1["id"] as $index => $key) {
$employee = array();
$occupation = in_array($key, $array2["id"]) ? $array2["occupation"][$index] : false;
if ($occupation === false) {
continue;
}
$employee["name"] = $key;
$employee["occupation"] = $occupation;
array_push($filter_array["employees"], $employee);
}
echo "<pre>" . print_r($filter_array, true) . "</pre>";
Second Solution
$array1 = array("id1" => array("names" => "name1"), "id2" => array("names" => "name2"), "id3" => array("names" => "name3"));
$array2 = array("id1" => array("occupation" => "occupation1"), "id2" => array("occupation" => "occupation2"), "id3" => array("occupation" => "occupation3"));
$filter_array = array("employees" => array());
foreach ($array1 as $key => $value) {
$employee = array();
if (!isset($array2[$key])) {
continue;
}
$employee["name"] = $value["names"];
$employee["occupation"] = $array2[$key]["occupation"];
array_push($filter_array["employees"], $employee);
}
echo "<pre>" . print_r($filter_array, true) . "</pre>";
i hope my code can help.
you can try this
$Array_1 = array(
'ID_1' => 'Michael',
'ID_2' => 'Jerry',
'ID_3' => 'Tony',
'ID_4' => 'Roger',
);
$Array_2 = array(
'ID_1' => 'Chef',
'ID_2' => 'Mechanic',
'ID_3' => 'Cook',
'ID_4' => 'Dealer',
);
$filter_array = array("employees" => array());
foreach($Array_1 as $key => $value){
$employee = array();
if(!isset($Array_2[$key])){ continue; }
$employee["name"] = $value;
$employee["occupation"] = $Array_2[$key];
array_push($filter_array["employees"], $employee);
}
EDIT 2
Aah, now I see the phpfiddle in the comments and the edit to the OP. So, the ID is already the key of the array? ... Then just do
foreach($Array_1 as $key_1 => $value_1) {
$new_Array[$key_1]['Names'] = $Array_1['Names'];
}
foreach($Array_2 as $key_2 => $value_2) {
$new_Array[$key_2]['Occupation'] = $Array_2['Occupation'];
}
use array_walk . It runs a function per each array item .combine them in the function .

PHP: Building multidimensional array

I have an array like this:
Array(
'level1' => 'someval',
'level2' => 'someotherval',
'level3' => 'thirdval'
)
I want to turn it into this:
Array(
'someval' => Array(
'someotherval' => Array(
'thirdval' => 1
)
)
)
Obviously I could build the example above by hand but I don't know how many levels there will be. And this simple example might seem useless, but there are going to be more values, so there will be multiple arrays inside each of the levels.
This will do it
$array = array(
'level1' => array(
'level2' => array(
'level3' => 1
)
)
);
Here's my take on it:
function make_multi_level_array($arr) {
if (count($arr) == 1) return array(array_pop($arr) => 1);
else {
$level_key = array_pop(array_reverse($arr));
$sub_level = make_multi_level_array(
array_slice($arr,1,count($arr)-1)
);
return array(
$level_key => $sub_level
);
}
}
$arr = array(
'level1' => 'someval',
'level2' => 'someotherval',
'level3' => 'thirdval',
);
var_dump(make_multi_level_array($arr));
Will output this:
array(1) {
["someval"]=>
array(1) {
["someotherval"]=>
array(1) {
["thirdval"]=>
int(1)
}
}
}
Also tried other cases like below.
$arr = array(
'level1' => 'someval',
'level2' => 'someotherval',
'level3' => 'thirdval',
'level4' => 'fourthval'
);
Seems okay:
array(1) {
["someval"]=>
array(1) {
["someotherval"]=>
array(1) {
["thirdval"]=>
array(1) {
["fourthval"]=>
int(1)
}
}
}
}
Do you need something like this?
$levels = array_keys(Array(
'level1' => 'someval',
'level2' => 'someotherval',
'level3' => 'thirdval'
));
$array = Array();
$aux = &$array;
foreach ($levels as $level => $value) {
if ($aux == 1)
$aux = array($value => 1);
$aux = &$aux[$value];
}
var_dump($array);

Categories