PHP Find string position in array - php

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.

Related

Extracting value from multidimensional array

$arrayDif = array();
$arrayDif[] = array('employer' => $employer,
'comment' => $comment,
'value' => $resultValue);
Filling in from a loop.
Below is the array that I have filled up. I need to be able to find a match by the 'employer' and 'comment' and extract the value, so I can re-update this value.
Array
(
[0] => Array
(
[employer] => Albury-Wodonga
[comment] => allOtherMembers
[value] => 7
)
[1] => Array
(
[employer] => Albury-Wodonga
[comment] => associateMembers
[value] => 1
)
One command to extract and re-update the value, I suggest to use foreach loop
<?php
$arrayDif = array();
$arrayDif[] = array('employer' => "AAA", 'comment' => "comment 1", 'value' => "1");
$arrayDif[] = array('employer' => "BBB", 'comment' => "comment 2", 'value' => "2");
$arrayDif[] = array('employer' => "CCC", 'comment' => "comment 3", 'value' => "3");
// function for setting the value or returning the value
// notice the $array here is a reference to the real array
function func(&$array, $employer, $comment, $value = ''){
// $v is also a reference
foreach ($array as $k => &$v) {
if($v['employer'] == $employer && $v['comment'] == $comment) {
if(empty($value)) {
return $v['value'];
} else {
$v['value'] = $value;
}
}
}
return "Not Found.";
}
//update
func($arrayDif, 'AAA', 'comment 1', "123123");
//search
echo func($arrayDif, 'AAA', 'comment 1');
?>
Not sure if this is what you are looking for but here you go. I would use a function and simple loop.
<?php
$arrayDif = array();
$arrayDif[] = array(
array('employer' => "Albury-Wodonga", 'comment' => "allOtherMembers", 'value' => "1 star"),
array('employer' => "Employer2", 'comment' => "Good Job", 'value' => "2 stars"),
array('employer' => "Employer3", 'comment' => "Smart", 'value' => "3 stars")
);
// Function for searching the array for the matches and returning the value of the match.
function SearchMe($array, $searchEmployer, $searchComment){
for($i = 0; $i < count($array); $i++){
for($j = 0; $j < count($array[$i]); $j++){
if(
$array[$i][$j]["employer"] == $searchEmployer &&
$array[$i][$j]["comment"] == $searchComment
){
return $array[$i][$j]["value"];
}
}
}
return "No Match";
}
echo SearchMe($arrayDif, "Albury-Wodonga", "allOtherMembers");
?>

Turn string to nested array php

I am trying to turn a string into a nested array
Here is my string:
a/b/d.docx
and I wanted to be like this:
array(
"name" => "a",
"type" => "folder",
"sub" => array(
"name" => "b",
"type" => "folder",
"sub" => array(
"name" => "c.docx",
"type" => "file",
"size" => "20"
)
)
)
This is the code that I have so far
$items = explode('/', $strings);
$num = count($items);
$num = --$num;
$temp = array();
foreach($items as $keys => $value) {
$temp[$keys] = array(
"name" => $value,
"type" => "folder",
"items" => $temp[++$keys]
);
if($keys == $num){
$temp[$keys] = array(
"name" => $value,
"type" => "file",
"size" => "20"
);
}
}
var_dump($temp);
I am trying this functions but this only turn string into a single array and it also can't do the 'items' line.
Any help would be appreciated.Thanks.
Note that the path is virtual and doesn't exist.
UPDATE: How can I add path to each array??for example,"path"=>"a/b"
You can do that:
$path = 'a/b/d.docx';
$parts = explode('/', $path);
$result = [ 'name' => array_pop($parts), 'type' => 'file', 'size' => 20 ];
while ($parts) {
$result = [ 'name' => array_pop($parts), 'type' => 'folder', 'sub' => $result ];
}
print_r($result);
<?php
$strings='a/b/d.docx';
$items = explode('/', $strings);
$num = count($items)-1;
$root= array();
$cur = &$root;
$v='';
foreach($items as $keys => $value) {
$v = $v.$value;
$temp = array( "name" => $value, "path"=>$v, "type" => "folder", "items" => "");
if($keys == $num){
$temp = array( "name" => $value, "path"=>$v, "type" => "file", "size" => "20");
}
$v= $v.'/';
if($keys==0) {
$cur = $temp;
}
else
{
$cur['items'] = $temp;
$cur = &$cur['items'];
}
}
var_dump($root);
Try recursion:
public function testAction(){
$sString = 'a/b/c/d.exe';
$aExploded = explode('/', $sString);
var_dump($this->_parse_folder_rec($aExploded));
}
private function _parse_folder_rec($aExploded){
$aResult = [];
$aResult['name'] = array_shift($aExploded);
if($aExploded){
$aResult['type'] = 'folder';
$aResult['sub'] = $this->_parse_folder_rec($aExploded);
}else{
$aResult['type'] = 'file';
$aResult['size'] = 20;
}
return $aResult;
}

If value between array key

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

PHP : multidimensional array merge recursive

I need to merge those two arrays:
$ar1 = array("color" => array("red", "green"), "aa");
$ar2 = array("color" => array( "green", "blue"), "bb");
$result = array_merge_recursive($ar1, $ar2);
Expected output:
[
'color' => [
(int) 0 => 'red',
(int) 1 => 'green',
(int) 3 => 'blue'
],
(int) 0 => 'aa',
(int) 1 => 'bb'
]
But it outputs:
[
'color' => [
(int) 0 => 'red',
(int) 1 => 'green',
(int) 2 => 'green', (!)
(int) 3 => 'blue'
],
(int) 0 => 'aa',
(int) 1 => 'bb'
]
I'm looking for the simplest way to do this, my array inputs won't be deeper than those examples.
Here it is.
function array_merge_recursive_ex(array $array1, array $array2)
{
$merged = $array1;
foreach ($array2 as $key => & $value) {
if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
$merged[$key] = array_merge_recursive_ex($merged[$key], $value);
} else if (is_numeric($key)) {
if (!in_array($value, $merged)) {
$merged[] = $value;
}
} else {
$merged[$key] = $value;
}
}
return $merged;
}
Thanks to Meglio comment, you can use these functions for any number of arrays :
Functions
function drupal_array_merge_deep() {
$args = func_get_args();
return drupal_array_merge_deep_array($args);
}
// source : https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/drupal_array_merge_deep_array/7.x
function drupal_array_merge_deep_array($arrays) {
$result = array();
foreach ($arrays as $array) {
foreach ($array as $key => $value) {
// Renumber integer keys as array_merge_recursive() does. Note that PHP
// automatically converts array keys that are integer strings (e.g., '1')
// to integers.
if (is_integer($key)) {
$result[] = $value;
}
elseif (isset($result[$key]) && is_array($result[$key]) && is_array($value)) {
$result[$key] = drupal_array_merge_deep_array(array(
$result[$key],
$value,
));
}
else {
$result[$key] = $value;
}
}
}
return $result;
}
Usage
$merged = drupal_array_merge_deep($ar_1, $ar_2);
var_dump($merged);
$merged = drupal_array_merge_deep_array([$ar_1, $ar_2]);
var_dump($merged);
Usage (test data)
$ar_1 = [
"item1" => false,
"item2" => true,
"item_list" => [
"sub_item1" => 5,
"sub_itemlist" => [
"sub_sub_item1" => 27,
],
]
];
$ar_2 = [
"item_list" => [
"sub_item2" => 5,
"sub_itemlist" => [
"sub_sub_item2" => 27,
],
],
"item3" => true,
];
Usage output (same for both functions)
array (size=4)
'item1' => boolean false
'item2' => boolean true
'item_list' =>
array (size=3)
'sub_item1' => int 5
'sub_itemlist' =>
array (size=2)
'sub_sub_item1' => int 27
'sub_sub_item2' => int 27
'sub_item2' => int 5
'item3' => boolean true

substr by using array as condition

I have a file contain text
ABBCDE1990-12-10JOBALPHABETabbcde1990-12-10jobalphabet
$field = array(
"fullname" => array("length"=5,"mandat"=>True),
"bithday" => array("length"=>10,"mandat"=>True)
"job" => array("length"=>3,"mandat"=>True),
"desc" => array("length"=>8,"mandat"=>false)
);
How can I get the array some thing like this:
$output = array(
//ABBCDE1990-12-10JOBALPHABET
0=>array(
"fullname" => "ABBCDE"
"bithday" => 1990-12-10
"job" => "JOB"
"desc"=> "ALPHABET"
)
//abbcde1990-12-10jobalphabet
1=>array(
"fullname" => "abbcde"
"bithday" => 1990-12-10
"job" => "job"
"desc"=> "alphabet"
)
);
I am tryin to buld a function
function toOutput($str,$filed){
$per_line = 27;//len of abbcde1990-12-10jobalphabet
$pos = 0;
while ($pos<strlen($str)){
$pos += 27;
//
}
}
$field = array(
"fullname" => array("length"=>6,"mandat"=>True),
"bithday" => array("length"=>10,"mandat"=>True),
"job" => array("length"=>3,"mandat"=>True),
"desc" => array("length"=>8,"mandat"=>false)
);
$string = 'ABBCDE1990-12-10JOBALPHABETabbcde1990-12-10jobalphabet';
$result = array();
$countString = strlen($string)/27;
$oldPos = 0;
for($i=0;$i<$countString;$i++) {
foreach($field as $k=>$v) {
$result[$i][$k] = substr($string,$oldPos,$v['length']);
$oldPos += $v['length'];
}
}
print_r($result);
You can see it up and running here: http://codepad.org/CEQNIPCg (version 0.3)
Based on that you can create a function so you can pass to it all $string that you have

Categories