Find one string and get related values - php

I have several strings, how can I search the first value and get other values from it?
print_r or ?:
Array( [0] => Title,11,11 [1] => Would,22,22 [2] => Post,55,55 [3] => Ask,66,66 )
like:
If send for this array value Title and getting values Title,11,11
Or send Would getting values Would,22,22
Or send Post getting values Post,55,55
Or send Ask getting values Ask,66,66
How can do it?

Loop over the array with foreach and match the value with strpos.

suppose:
$arr = Array( [0] => Title,11,11 [1] => Would,22,22 [2] => Post,55,55 [3] => Ask,66,66 )
$string = 'Would';
then
//Call the function with the search value in $string and the actual array
$required_arr[$string] = search_my_array($string, $arr);
function($str , $array)
{
//Trace the complete array
for($i = 0; $i<count($array); $i++)
{
//Break the array using explode function based on ','
$arr_values[$i] = explode(',',$array[i])
if($str == $arr_values[$i][0]) // Match the First String with the required string
{
//On match return the array with the values contained in it
return array($arr_values[$i][1], $arr_values[$i][2]);
}
}
}
Now
$required_arr['Would'] // will hold Array([0] => 22 [1] => 22)

Write a function to search the array. This should work well enough
<?php
// test array
$arr = array('Title,11,11','Would,22,22','Post,55,55','Ask,66,66');
// define search function that you pass an array and a search string to
function search($needle,$haystack){
// loop over each passed in array element
foreach($haystack as $v){
// if there is a match at the first position
if(strpos($v,$needle) === 0)
// return the current array element
return $v;
}
// otherwise retur false if not found
return false;
}
// test the function
echo search("Would",$arr);
?>

are the indices important ? why not ..
$arr = array(
'Title' => array(11, 11),
'Would' => array(22, 22),
'Post' => array(55, 55),
'Ask' => array(66,66)
);
$send = "Title"; // for example
$result = $arr[$send];

How about using something like, so you don't loop trough entire array:
$array = array( "Title,11,11", "Would,22,22", "Post,55,55", "Ask,66,66" );
$key = my_array_search('Would', $array);
$getvalues = explode(",", $array[$key]);
function my_array_search($needle = null, $haystack_array = null, $skip = 0)
{
if($needle == null || $haystack_array == null)
die('$needle and $haystack_array are mandatory for function my_array_search()');
foreach($haystack_array as $key => $eval)
{
if($skip != 0)$eval = substr($eval, $skip);
if(stristr($eval, $needle) !== false) return $key;
}
return false;
}

Related

PHP group certain results from foreach on array into another array

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

Combine post values and remove empty

I have two sets of arrays coming from $_POST. Keys for both will be numeric and the count will be the same, since they come in pairs as names and numbers:
$_POST[names]
(
[0] => First
[1] => Second
[2] =>
[3] => Fourth
)
$_POST[numbers]
(
[0] => 10
[1] =>
[2] => 3
[3] => 3
)
Now I need to combine those two, but remove each entry where either values are missing.
The result should be something like:
$finalArray
(
[First] => 10
[Fourth] => 3
)
Post data is dynamically created so there might be different values missing based on user input.
I tried doing something like:
if (array_key_exists('names', $_POST)) {
$names = array_filter($_POST['names']);
$numbers = array_filter($_POST['numbers']);
if($names and $numbers) {
$final = array_combine($names, $numbers);
}
}
But I can't seem to filter it correctly, since its giving me an error:
Warning: array_combine(): Both parameters should have an equal number of elements
How about using array_filter with ARRAY_FILTER_USE_BOTH flag on?
<?php
$array1 = [
0 => "First",
1 => "Second",
2 => "",
3 => "Fourth",
];
$array2 = [
0 => 10,
1 => "",
2 => 3,
3 => 3,
];
var_dump(array_filter(array_combine($array1, $array2), function($value, $key) {
return $key == "" || $value == "" ? false : $value;
}, ARRAY_FILTER_USE_BOTH ));
/*
Output:
array(2) {
["First"]=>
int(10)
["Fourth"]=>
int(3)
}
*/
Here's a fun way:
$result = array_flip(array_flip(array_filter(array_combine($_POST['names'],
$_POST['numbers']))));
// create array using $_POST['names'] as keys and $_POST['numbers'] as values
$result = array_combine($_POST['names'], $_POST['numbers']);
// remove entries that have empty values
$result = array_filter($result);
// remove entry with empty key
unset($result[null]);
print_r($result);
If both arrays will have the same count, and the keys will always be numeric, you could do the following:
$total = count($_POST['names']);
$final = array();
for ($i = 0; $i < $total; $i++) {
if (trim($_POST['names'][$i]) != '' && trim($_POST['numbers'][$i]) != '') {
$final[$_POST['names'][$i]] = $_POST['numbers'][$i];
}
}
Or if you prefer to use a foreach instead of for
$final = array();
foreach ($_POST['names'] as $key => $value) {
if (trim($value) != '' && trim($_POST['numbers'][$key]) != '') {
$final[$value] = $_POST['numbers'][$key];
}
}
Takeing your previous information into account:
both keys will be numeric and the count will be the same, since they come in pairs as names and numbers
$myNewArray = array();
$count = 0;
foreach ($_POST['names'] as $bufferArray)
{
if (($bufferArray[$count]!=NULL)&&($_POST['numbers][$count]!=NULL))
{
array_push($myNewArray, array($bufferArray[$count] => $_POST['numbers][$count]);
}
$count++;
}
Let me know if that helps! :)
Note: I made some edits to the code.
Also, my previous code checks if the empty array spaces are NULL. If you want to check if they are either NULL or "" (empty), then replace the line of code with:
if (($bufferArray[$count]!=NULL)&&($_POST['numbers][$count]!=NULL)&&($bufferArray[$count]!="")&&($_POST['numbers][$count]!=""))
{...}

PHP array grouping values

I have an array like below
array(0=>A,1=>A,2=>B,3=>B,4=>C,5=>A,6=>A)
My problem is i need to group the same value with multiple occurrence. For example for the above question I need an array like array('A' => (count1=>2,count2=>2), 'B' => (count1=>2), 'C' => (count1=>1)). How can i loop the array
$data = array(0=>A,1=>A,2=>B,3=>B,4=>C,5=>A,6=>A);
$counters = array();
$prev = NULL;
array_walk(
$data,
function ($entry) use (&$prev, &$counters) {
if ($entry !== $prev) {
$prev = $entry;
$counters[] = 1;
} else {
$counters[count($counters)-1]++;
}
}
);
var_dump($counters);
If you need the frequency of values in the array, there is a php function for that called
array_count_values($array).
In case of your example,
$data = array(0=>'A',1=>'A',2=>'B',3=>'B',4=>'C',5=>'A',6=>'A');
print_r(array_count_values($data));
would output
Array
(
[A] => 4
[B] => 2
[C] => 1
)
here is the answer -
$arr=array(0=>A,1=>A,2=>B,3=>B,4=>C,5=>A,6=>A);
$count=array();$passedelement=array();$pastelement='';$n=0;$k=0;$presentflag=0;
for($i=0;$i<7;$i++){
if($pastelement==$arr[$i]){$presentflag=1;}
if($presentflag==0){
$pastelement=$arr[$i];
$passedelement[$k++]=$arr[$i];
for($j=$i;$j<7;$j++){
if($arr[$i]==$arr[$j]){$count[$n]+=1;}else{break;}
}
$n++;
}
$presentflag=0;
}
print_r($passedelement);
print_r($count);

Removing object from array; how to avoid nulls

I have an array that is a object which I carry in session lifeFleetSelectedTrucksList
I also have objects of class fleetUnit
class fleetUnit {
public $idgps_unit = null;
public $serial = null;
}
class lifeFleetSelectedTrucksList {
public $arrayList = array();
}
$listOfTrucks = new lifeFleetSelectedTrucksList(); //this is the array that I carry in session
if (!isset($_SESSION['lifeFleetSelectedTrucksList'])) {
$_SESSION['lifeFleetSelectedTrucksList'] == null; //null the session and add new list to it.
} else {
$listOfTrucks = $_SESSION['lifeFleetSelectedTrucksList'];
}
I use this to remove element from array:
$listOfTrucks = removeElement($listOfTrucks, $serial);
And this is my function that removes the element and returns the array without the element:
function removeElement($listOfTrucks, $remove) {
for ($i = 0; $i < count($listOfTrucks->arrayList); $i++) {
$unit = new fleetUnit();
$unit = $listOfTrucks->arrayList[$i];
if ($unit->serial == $remove) {
unset($listOfTrucks->arrayList[$i]);
break;
} elseif ($unit->serial == '') {
unset($listOfTrucks->arrayList[$i]);
}
}
return $listOfTrucks;
}
Well, it works- element gets removed, but I have array that has bunch of null vaues instead. How do I return the array that contains no null elements? Seems that I am not suing something right.
I think what you mean is that the array keys are not continuous anymore. An array does not have "null values" in PHP, unless you set a value to null.
$array = array('foo', 'bar', 'baz');
// array(0 => 'foo', 1 => 'bar', 2 => 'baz');
unset($array[1]);
// array(0 => 'foo', 2 => 'baz');
Two approaches to this:
Loop over the array using foreach, not a "manual" for loop, then it won't matter what the keys are.
Reset the keys with array_values.
Also, removing trucks from the list should really be a method of $listOfTrucks, like $listOfTrucks->remove($remove). You're already using objects, use them to their full potential!
You can use array_filter
<?php
$entry = array(
0 => 'foo',
1 => false,
2 => -1,
3 => null,
4 => ''
);
print_r(array_filter($entry));
?>
output:
Array
(
[0] => foo
[2] => -1
)

PHP: Get n-th item of an associative array

If you have an associative array:
Array
(
[uid] => Marvelous
[status] => 1
[set_later] => Array
(
[0] => 1
[1] => 0
)
[op] => Submit
[submit] => Submit
)
And you want to access the 2nd item, how would you do it? $arr[1] doesn't seem to be working:
foreach ($form_state['values']['set_later'] as $fieldKey => $setLater) {
if (! $setLater) {
$valueForAll = $form_state['values'][$fieldKey];
$_SESSION[SET_NOW_KEY][array_search($valueForAll, $form_state['values'])] = $valueForAll; // this isn't getting the value properly
}
}
This code is supposed to produce:
$_SESSION[SET_NOW_KEY]['status'] = 1
But it just produces a blank entry.
Use array_slice
$second = array_slice($array, 1, 1, true); // array("status" => 1)
// or
list($value) = array_slice($array, 1, 1); // 1
// or
$blah = array_slice($array, 1, 1); // array(0 => 1)
$value = $blah[0];
I am a bit confused. Your code does not appear to have the correct keys for the array. However, if you wish to grab just the second element in an array, you could use:
$keys = array_keys($inArray);
$key = $keys[1];
$value = $inArray[$key];
However, after considering what it appears you're trying to do, something like this might work better:
$ii = 0;
$setLaterArr = $form_state['values']['set_later'];
foreach($form_state['values'] as $key => $value) {
if($key == 'set_later')
continue;
$setLater = $setLaterArr[$ii];
if(! $setLater) {
$_SESSION[SET_NOW_KEY][$key] = $value;
}
$ii ++;
}
Does that help? It seems you are trying to set the session value if the set_later value is not set. The above code does this. Instead of iterating through the inner array, however, it iterates through the outer array and uses an index to track where it is in the inner array. This should be reasonably performant.
You can use array_slice to get the second item:
$a= array(
'hello'=> 'world',
'how'=> 'are you',
'an'=> 'array',
);
$second= array_slice($a, 1, 1, true);
var_dump($second);
Here's a one line way to do it with array_slice and current
$value = current(array_slice($array, 1, 1)); // returns value only
If the array you provide in the first example corresponds to $form_state then
$form_state['values']['set_later'][1]
will work.
Otherwise
$i = 0;
foreach ($form_state['values']['set_later'] as $fieldKey => $setLater) {
if ($i == 1) {
$valueForAll = $form_state['values'][$fieldKey];
$_SESSION[SET_NOW_KEY][$fieldKey] = $setLater;
continue;
}
$i++;
}
Every one of the responses here are focused on getting the second element, independently on how the array is formed.
If this is your case.
Array
(
[uid] => Marvelous
[status] => 1
[set_later] => Array
(
[0] => 1
[1] => 0
)
[op] => Submit
[submit] => Submit
)
Then you can get the value of the second element via $array['status'].
Also this code
foreach ($form_state['values']['set_later'] as $fieldKey => $setLater) {
if (! $setLater) {
$valueForAll = $form_state['values'][$fieldKey];
$_SESSION[SET_NOW_KEY][array_search($valueForAll, $form_state['values'])] = $valueForAll; // this isn't getting the value properly
}
}
I don't understand what are you trying to do, care to explain?
/**
* Get nth item from an associative array
*
*
* #param $arr
* #param int $nth
*
* #return array
*/
function getNthItemFromArr($arr, $nth = 0){
$nth = intval($nth);
if(is_array($arr) && sizeof($arr) > 0 && $nth > 0){
$arr = array_slice($arr,$nth-1, 1, true);
}
return $arr;
}//end function getNthItemFromArr

Categories