I have the following array called $submissions:
Array ( [0] => 342 [1] => 343 [2] => 344 [3] => 345 )
I then have a string:
$in_both = 342,344;
I then am using this code to remove any number thats in $in_both from $submissions:
if(($key = array_search($in_both, $submissions)) !== false) {
unset($submissions[$key]);
}
The problem is this is only working for the first number.
How can I have all the numbers removed from the array that are in the variable $in_both?
Thank you
Since in_both is a string, you need to convert it to an array:
$in_both_arr = explode(",",$in_both);
Then you can compare the arrays:
$submissions = array_diff($submissions,$in_both_arr);
See documentation.
Try this:
$submissions = Array( 342, 343, 344, 345 );
$in_both = '342,344';
$needles = explode(',', $in_both);
foreach ($needles as $needle) {
while (($key = array_search($needle, $submissions)) !== false) {
unset($submissions[$key]);
}
}
The while inside the foreach guarantees that every occurence of the number in the array will be removed.
Try with:
$submissions = array(342, 343, 344, 355);
$in_both = '342,344';
foreach ( explode(',', $in_both) as $value ) {
if(($key = array_search($value, $submissions)) !== false) {
unset($submissions[$key]);
}
}
you have to use expolde function with "," delimiter , and loop through arrary created by explode as follow
$in_both = "342,344";
$in_both_arr = explode(",",$in_both);
foreach($in_both_arr as $val)
if(($key = array_search($val, $submissions)) !== false) {
unset($submissions[$key]);
}
}
Related
I have an array that looks something like this:
$array = array( [0] => FILE-F01-E1-S01.pdf
[1] => FILE-F01-E1-S02.pdf
[2] => FILE-F01-E1-S03.pdf
[3] => FILE-F01-E1-S04.pdf
[4] => FILE-F01-E1-S05.pdf
[5] => FILE-F02-E1-S01.pdf
[6] => FILE-F02-E1-S02.pdf
[7] => FILE-F02-E1-S03.pdf );
Basically, I need to look at the first file and then get all the other files that have the same beginning ('FILE-F01-E1', for example) and put them into an array. I don't need to do anything with the other ones at this point.
I've been trying to use a foreach loop finding the previous value to do this, but am not having any luck.
Like this:
$previousFile = null;
foreach($array as $file)
{
if(substr_replace($previousFile, "", -8) == substr_replace($file, "", -8))
{
$secondArray[] = $file;
}
$previousFile = $file;
}
So then $secondArray would look like this:
Array ( [0] => FILE-F01-E1-S01.pdf [1] => FILE-F01-E1-S02.pdf
[2] => FILE-F01-E1-S03.pdf [3] => FILE-F01-E1-S04.pdf
[4] => FILE-F01-E1-S05.pdf)
As my result.
Thank you!
You can use array_filter combined with strpos:
$result = array_filter($array, function($filename) {
return strpos($filename, 'FILE-F01-E1') === 0;
});
Are you sure this will be the naming format? That is crucial information to have to construct a regexp or something to check for being a substring of the following strings.
If we can assume this and that the "base" name is always at index 0 then you could do something like.
<?php
$myArr = [
'FILE-F01-E1-S01.pdf',
'FILE-F01-E1-S02.pdf',
'FILE-F01-E1-S03.pdf',
'FILE-F01-E1-S04.pdf',
'FILE-F01-E1-S05.pdf',
'FILE-F02-E1-S01.pdf',
'FILE-F02-E1-S02.pdf',
'FILE-F02-E1-S03.pdf'
];
$baseName = '';
$allSimilarNames = [];
foreach($myArr as $index => &$name) {
if($index == 0) {
$baseName = substr($name, 0, strrpos($name, '-'));
$allSimilarNames[] = $name;
}
else {
if(strpos($name, $baseName) === 0) {
$allSimilarNames[] = $name;
}
}
}
var_dump($allSimilarNames);
This will
Check at index one to get the base name to compare against
Loop all items in the array and match all items, no matter where in the array they are, that are similar according to your naming convention
So if you next time have an array that is
$myArr = [
'FILE-F02-E1-S01.pdf',
'FILE-F01-E1-S01.pdf',
'FILE-F01-E1-S02.pdf',
'FILE-F01-E1-S03.pdf',
'FILE-F01-E1-S04.pdf',
'FILE-F01-E1-S05.pdf',
'FILE-F02-E1-S02.pdf',
'FILE-F02-E1-S03.pdf'
];
this will return all the items that match FILE-F02-E1*.
You could also make a small function of it for easier use and not have to rely on the element at index 0 having to be the "base" name.
<?php
function findMatches($baseName, &$names) {
$matches = [];
$baseName = substr($baseName, 0, strrpos($baseName, '-'));
foreach($names as &$name) {
if(strpos($name, $baseName) === 0) {
$matches[] = $name;
}
}
return $matches;
}
$myArr = [
'FILE-F01-E1-S01.pdf',
'FILE-F01-E1-S02.pdf',
'FILE-F01-E1-S03.pdf',
'FILE-F01-E1-S04.pdf',
'FILE-F01-E1-S05.pdf',
'FILE-F02-E1-S01.pdf',
'FILE-F02-E1-S02.pdf',
'FILE-F02-E1-S03.pdf'
];
$allSimilarNames = findMatches('FILE-F01-E1-S01.pdf', $myArr);
var_dump($allSimilarNames);
Run a simple foreach with strpos() which looks for an occurrence of a string within a string.
$results = array();
foreach($array as $item){
if (strpos($item, 'FILE-F01-E1') === 0) {
array_push($results, $item);
}
}
You could get the first item from the array and use explode and implode to get the part from the filename without the last hyphen and the content after that.
Then use array_filter and use substr using 0 as the start position and the length of the $fileBeginning as the length to check if the string starts with FILE-F01-E1:
$array = [
'FILE-F01-E1-S01.pdf',
'FILE-F01-E1-S02.pdf',
'FILE-F01-E1-S03.pdf',
'FILE-F01-E1-S04.pdf',
'FILE-F01-E1-S05.pdf',
'FILE-F02-E1-S01.pdf',
'FILE-F02-E1-S02.pdf',
'FILE-F02-E1-S03.pdf',
"TESTFILE-F01-E1-S03.pdf"
];
$parts = explode('-', $array[0]);
array_pop($parts);
$fileBeginning = implode('-', $parts);
$secondArray = array_filter($array, function ($x) use ($fileBeginning) {
return substr($x, 0, strlen($fileBeginning)) === $fileBeginning;
});
print_r($secondArray);
Result
Array
(
[0] => FILE-F01-E1-S01.pdf
[1] => FILE-F01-E1-S02.pdf
[2] => FILE-F01-E1-S03.pdf
[3] => FILE-F01-E1-S04.pdf
[4] => FILE-F01-E1-S05.pdf
)
Demo
I'm trying to get a useable array.
This is what I did to get the following array from my .csv file.
$csv = array_map('str_getcsv', file($file));
array_walk($csv, function(&$a) use ($csv) {
$a = array_combine($csv[0], $a);
});
array_shift($csv);
Right now I've got an array with these keys and values:
[0] => Array
(
[Label;Account;Registered;Licensed;User;UserLicense] => Test;Test;No;No;test;no;
)
And I want to get an array like:
[0] => Array
(
[Label] => Test
[Account] => Test
[Registered] => No
[Licensed] => No
[User] => test
[UsreLicense] => no
)
Can anyone help me?
Thanks.
class arrCsv {
private $arr;
private function getValFromArray($item, $key) {
$arrKeys = explode(';', $key);
$arrVal = explode(';', $item);
array_pop($arrVal); // remove last empty item
$this->arr[] = array_combine($arrKeys, $arrVal);
}
function setNewArr($arItems) {
array_walk_recursive($arItems, array($this, 'getValFromArray'));
}
function getNewArr() {
return $this->arr;
}
}
$r = new arrCsv;
$r->setNewArr($csvArray);
$vals = $r->getNewArr();
The answer I found:
$usersCsv = array();
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$usersCsv[] = $data;
array_walk($usersCsv, function(&$a) use ($usersCsv) {
$a = array_combine($usersCsv[0], $a);
});
}
fclose($handle);
array_splice($usersCsv, 0, 1);
}
Thanks for the help anyways!
I'm having a problem with this. I have a string that looks like this:
coilovers[strut_and_individual_components][complete_strut][][achse]
And i want to convert it to to array that looks like this:
[coilovers] => Array
(
[strut_and_individual_components] => Array
(
[complete_strut]=> Array
(
[1] => Array
(
[achse] => some_value
)
[2] => Array
(
[achse] => some_value
)
)
)
)
is it possible?
Here is a quick implementation of a parser that will attempt to parse this string:
$input = 'coilovers[strut_and_individual_components][complete_strut][][achse]';
$output = array();
$pointer = &$output;
while( ($index = strpos( $input, '[')) !== false) {
if( $index != 0) {
$key = substr( $input, 0, $index);
$pointer[$key] = array();
$pointer = &$pointer[$key];
$input = substr( $input, $index);
continue;
}
$end_index = strpos( $input, ']');
$array_key = substr( $input, $index + 1, $end_index - 1);
$pointer[$array_key] = array();
$pointer = &$pointer[$array_key];
$input = substr( $input, $end_index + 1);
}
print_r( $output);
Essentially, we are iterating the string to find matching [ and ] tags. When we do, we take the value within the brackets as $array_key and add that into the $output array. I use another variable $pointer by reference that is pointing to the original $output array, but as the iteration goes, $pointer points to the last element added to $output.
It produces:
Array
(
[coilovers] => Array
(
[strut_and_individual_components] => Array
(
[complete_strut] => Array
(
[] => Array
(
[achse] => Array
(
)
)
)
)
)
)
Note that I've left the implementation of [] (an empty array key) and setting the values in the last index (some_value) as an exercise to the user.
Well I've found an another answer for it and it looks like this:
private function format_form_data(array $form_values) {
$reformat_array = array();
$matches = array();
$result = null;
foreach($form_values as $value) {
preg_match_all("/\[(.*?)\]/", $value["name"], $matches);
$parsed_product_array = $this->parse_array($matches[1], $value["value"]);
$result = array_push($reformat_array, $parsed_product_array);
}
return $result;
}
private function parse_array(array $values, $value) {
$reformat = array();
$value_carrier_key = end($values);
foreach (array_reverse($values) as $arr) {
$set_value_carrier = array($arr => $reformat);
if($arr == $value_carrier_key) {
$set_value_carrier = array($arr => $value);
}
$reformat = empty($arr) ? array($reformat) : $set_value_carrier;
}
return $reformat;
}
where array $form_values is:
Array
(
[name] => '[coilovers][strut_and_individual_components][complete_strut][][achse]',
[value] => 'some_value'
)
No. If you evaluate the string you will get invalid PHP.
If you want to store a PHP Array as string and get it loaded back as PHP Array, have a look at serialize and unserialize functions.
Of course you can build an array from your string, but you'll have to write a parser.
The solution I propose:
function format_form_data(array $data) {
$matches = array();
$result = [];
foreach($data as $key => $value) {
preg_match_all("/\[(.*?)\]/", $key, $matches);
$matches = array_reverse($matches[1]);
$matches[] = substr( $key, 0, strpos($key, '['));;
foreach ($matches as $match) {
$value = [$match=>$value];
}
$result = array_replace_recursive($result, $value);
}
return $result;
}
I have been trying to get the value of my combined rate, but running into some trouble with simply getting the value :
Array ( [0] => Array ( [ZipCode] => 01014 [CombinedRate] => 0.0625 ) ) <--- this is the array that is printed.
Here is the full code:
<?php
function csv_to_array($filename= '', $delimiter=',')
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
$zipsearch = csv_to_array($_SERVER['DOCUMENT_ROOT'].'/textfiles/taxes.csv');
function search($array, $key, $value)
{
$results = array();
if (is_array($array)) {
if (isset($array[$key]) && $array[$key] == $value) {
$results[] = $array;
}
foreach ($array as $subarray) {
$results = array_merge($results, search($subarray, $key, $value));
}
}
return $results;
}
$valueofzip = search( $zipsearch, 'ZipCode', '01014');
print_r($valueofzip)
/*
Need Code To print Just value of that array
*/
?>
I just need the value of the combined rate after the zipcode is found from the array that is printed, but for whatever reason I am just missing it,
How do I just get the value of "Combined Rate" from this array that is printed : Array ( [0] => Array ( [ZipCode] => 01014 [CombinedRate] => 0.0625 ) )
Essentially this page will print out a single tax rate
It looks like the value that you are trying to retrieve is simply:
$valueofzip[0]['CombinedRate']
i.e. the value with the key "CombinedRate" in the zeroth element of $valueofzip.
If you are anticipating there being more than one array returned by your search function, then a foreach loop would be more appropriate:
foreach($valueofzip as $zip) {
if (isset($zip['CombinedRate'])) echo $zip['CombinedRate'];
}
Depending on exactly what you want to do with the value, you might also want to take a look at array_walk, array_map, etc. in the documentation. They can be used to traverse the array and apply a callback function to each element. For example:
$valueofzip = array(array("ZipCode" => 01014, "CombinedRate" => 0.0625),
array("ZipCode" => 02025, "CombinedRate" => 0.125 ));
$combined_rates = array_map(function($x) { if (isset($x['CombinedRate'])) return $x['CombinedRate']; }, $valueofzip));
print_r($combined_rates);
Output:
Array
(
[0] => 0.0625
[1] => 0.125
)
I have a multidimensional array e.g. (this can be many levels deep):
$array = Array (
[21] => Array ( )
[24] => Array (
[22] => Array ( )
[25] => Array (
[26] => Array ( )
)
)
)
I am trying to loop through it to see if a certain key exists:
$keySearch = 22; // key searching for
function findKey($array, $keySearch) {
foreach ($array as $item){
if (isset($item[$keySearch]) && false === findKey($item[$keySearch], $item)){
echo 'yes, it exists';
}
}
}
findKey($array, $keySearch);
But it finds nothing. Is there an error in the loop?
array_key_exists() is helpful.
Then something like this:
function multiKeyExists(array $arr, $key) {
// is in base array?
if (array_key_exists($key, $arr)) {
return true;
}
// check arrays contained in this array
foreach ($arr as $element) {
if (is_array($element)) {
if (multiKeyExists($element, $key)) {
return true;
}
}
}
return false;
}
Working example: http://codepad.org/GU0qG5su
I played with your code to get it working :
function findKey($array, $keySearch)
{
foreach ($array as $key => $item) {
if ($key == $keySearch) {
echo 'yes, it exists';
return true;
} elseif (is_array($item) && findKey($item, $keySearch)) {
return true;
}
}
return false;
}
Here is a one line solution:
echo strpos(json_encode($array), $key) > 0 ? "found" : "not found";
This converts the array to a string containing the JSON equivalent, then it uses that string as the haystack argument of the strpos() function and it uses $key as the needle argument ($key is the value to find in the JSON string).
It can be helpful to do this to see the converted string: echo json_encode($array);
Be sure to enclose the needle argument in single quotes then double quotes because the name portion of the name/value pair in the JSON string will appear with double quotes around it. For instance, if looking for 22 in the array below then $key = '"22"' will give the correct result of not found in this array:
$array =
Array (
21 => Array ( ),
24 =>
Array (
522 => Array ( ),
25 =>
Array (
26 => Array ( )
)
)
);
However, if the single quotes are left off, as in $key = "22" then an incorrect result of found will result for the array above.
EDIT: A further improvement would be to search for $key = '"22":'; just incase a value of "22" exists in the array. ie. 27 => "22" In addition, this approach is not bullet proof. An incorrect found could result if any of the array's values contain the string '"22":'
function findKey($array, $keySearch)
{
// check if it's even an array
if (!is_array($array)) return false;
// key exists
if (array_key_exists($keySearch, $array)) return true;
// key isn't in this array, go deeper
foreach($array as $key => $val)
{
// return true if it's found
if (findKey($val, $keySearch)) return true;
}
return false;
}
// test
$array = Array (
21 => Array ( 24 => 'ok' ),
24 => Array (
22 => Array ( 29 => 'ok' ),
25 => Array (
26 => Array ( 32 => 'ok' )
)
)
);
$findKeys = Array(21, 22, 23, 24, 25, 26, 27, 28, 29, 30);
foreach ($findKeys as $key)
{
echo (findKey($array, $key)) ? 'found ' : 'not found ';
echo $key.'<br>';
}
returns false if doesn't exists, returns the first instance if does;
function searchArray( array $array, $search )
{
while( $array ) {
if( isset( $array[ $search ] ) ) return $array[ $search ];
$segment = array_shift( $array );
if( is_array( $segment ) ) {
if( $return = searchArray( $segment, $search ) ) return $return;
}
}
}
return false;
}
For sure some errors, is this roughly what you are after? (Untested code):
$keySearch=22; // key seraching for
function findKey($array, $keySearch)
{
// check whether input is an array
if(is_array($array)
{
foreach ($array as $item)
{
if (isset($item[$keySearch]) || findKey($item, $keysearch) === true)
{
echo 'yes, it exists';
return true;
}
}
}
}
Here is one solution that finds and return the value of the key in any dimension array..
function findValByKey($arr , $keySearch){
$out = null;
if (is_array($arr)){
if (array_key_exists($keySearch, $arr)){
$out = $arr[$keySearch];
}else{
foreach ($arr as $key => $value){
if ($out = self::findValByKey($value, $keySearch)){
break;
}
}
}
}
return $out;
}
I did modified to return value of searched key:
function findKeyInArray($array, $keySearch, &$value)
{
foreach ($array as $key => $item) {
if ($key === $keySearch) {
$value = $item;
break;
} elseif (is_array($item)) {
findKeyInArray($item, $keySearch,$value);
}
}
}
$timeZone = null;
findKeyInArray($request, 'timezone', $timeZone);