php select index where array contains - php

is there a function out there to search in a array if it contains a part of a text
just like the jquery(':contains')
and then return the index it is in :)
here is an example to help you visualise it :)
$arr = array(
[0] => 'hello world',
[1] => 'foo',
[2] => 'bar',
);
$a = arr_contains('o',$arr); //returns array(1,0);
$b = arr_contains('fo',$arr);//return array(1);
$c = arr_contains('a',$arr);//return array(2);
$d = arr_contains('hello',$arr);//return array(0);
if recursively can be done would be a plus :)

Nope, you will have to write a custom function for matching by substring:
function arr_contains($str, $arr) {
$ret = array();
foreach ($arr as $k => $v) {
if (is_array($v)) {
if ($subarr = arr_contains($str, $v)) {
$ret[] = $subarr;
}
} else if (strpos($v, $str) !== false) {
$ret[] = $k;
}
}
return $ret;
}

Related

Recursively remove element by value

So I have the following array:
$array = array(array('fruit1' => 'apple'),
array('fruit2' => 'orange'),
array('veg1' => 'tomato'),
array('veg2' => 'carrot'));
and I want to run a function like this:
array_remove_recursive($array, 'tomato');
so the output is this:
$array = array(array('fruit1' => 'apple'),
array('fruit2' => 'orange'),
array('veg2' => 'carrot')); // note: the entire array containing tomato has been removed!
Is this solvable?
This will recursively unset the matching variable at any depth and then remove the parent element only if it is empty.
function recursive_unset(array &$array, $unwanted_val) {
foreach ($array as $key => &$value) {
if (is_array($value)) {
recursive_unset($value, $unwanted_val);
if(!count($value)){
unset($array[$key]);
}
} else if($value == $unwanted_val){
unset($array[$key]);
}
}
}
Function to remove recursively many values from multidimensional array.
# Example 1
$arr1 = array_remove_recursive($arr, 'tomato');
# Example 2
$arr2 = array_remove_recursive($arr, ['tomato', 'apple']);
function array_remove_recursive($arr, $values)
{
if (!is_array($values))
$values = [$values];
foreach ($arr as $k => $v) {
if (is_array($v)) {
if ($arr2 = array_remove_recursive($v, $values))
$arr[$k] = $arr2;
else
unset($arr[$k]);
} elseif (in_array($v, $values, true))
unset($arr[$k]);
}
return $arr;
}
function array_remove_recursive($getArray,$getAssocValue)
{
$returnArray = array();
if(is_array($getArray))
{
foreach($getArray as $indAssocValue)
{
if(is_array($indAssocValue))
{
foreach($indAssocValue as $innerKey=>$innerVal)
{
if($innerVal!=$getAssocValue and $innerKey!="")
{
$returnArray[] = array("$innerKey"=>$innerVal);
}
}
}
}
}
return $returnArray;
}
$array = array(array('fruit1' => 'apple'),
array('fruit2' => 'orange'),
array('veg1' => 'tomato'),
array('veg2' => 'carrot'));
print_r($array);
echo "<br />";
$array = array_remove_recursive($array, 'tomato');
print_r($array);
hope the above code would be helpfull.

Array manipulation (PHP)

I have an array like this one :
Array
{
'property1.subproberty11' => "xxxxx",
'property1.subproberty12' => "yyyy",
'property2.subproberty21.subproperty211' => "zzzzzz",
'property2.subproberty21.subproperty212' => "wwwww",
'property2.subproberty22' => "yyyy",
....
That needs to be changed into something like :
Array
(
[property1] => Array
(
['subproberty11'] => "xxxxx"
['subproberty12'] => "yyyy"
)
[property2] => Array
(
[subproperty21] => Array
(
[subproperty211] => "zzzzzz"
[subproperty212] => "wwwwww"
)
['subproberty22'] => "yyyy"
)
...
I can't find a smart way of doing this, can someone help me ?
So, far, i have thought of this kind of algorithm :
$new_array = array();
foreach($old_array as $key => $value)
{
$subkeys = explode('.', $key);
$ss = array();
for($ii = 0 ; $ii < count($subkeys) ; $ii++)
{
$ss[] = "['".$subkeys[$ii]."']";
if ($ii < count($subkeys) -1)
eval('$new_array'.implode('',$ss).' = array();');
}
eval('$new_array'.implode('',$ss)." = '".$value."';');
}
I think we can do better, for example maybe we can avoid duplicating data by creating a new array ?
My working example:
function nestedKeysArray($input) {
$array = array();
foreach ($input as $key => $value) {
$keys = explode('.', $key);
if (count($keys) == 1) {
$array[$key] = $value;
} else {
$nested = &$array;
foreach ($keys as $k) {
if (!isset($nested[$k]))
$nested[$k] = array();
$nested = &$nested[$k];
}
$nested = $value;
}
}
return $array;
}
$input is array like first one from the question.
EDIT:
Changing original array, without copy:
function nestedKeysArray(&$input) {
foreach ($input as $key => $value) {
$keys = explode('.', $key);
if (count($keys) > 1) {
$nested = &$input;
foreach ($keys as $k) {
if (!isset($nested[$k]))
$nested[$k] = array();
$nested = &$nested[$k];
}
$nested = $value;
unset($input[$key]);
}
}
}
Some untested code, to give you the direction you could take.
Just loop through the array;
function SplitArray($properties) {
foreach($properties as $item=>$property) {
$properties[$item] = explode('.',$property, 2);
if(strpos($properties[$item][1], '.') === false)) {}
else {
$properties[$item][1] = SplitArray($properties[$item][1]);
}
}
return $properties;
}

Reverse flatted array to multidimensional

In another thread i asked about flatten an array with a specific style to get something like this:
array(4) {
["one"]=> string(9) "one_value"
["two-four"]=> string(10) "four_value"
["two-five"]=> string(10) "five_value"
["three-six-seven"]=> string(11) "seven_value"
}
I've got some very good help there, but now im wondering how would i reverse this method to get again the same original array:
array(
'one' => 'one_value',
'two' => array
(
'four' => 'four_value',
'five' => 'five_value'
),
'three' => array
(
'six' => array
(
'seven' => 'seven_value'
)
)
)
I've tried with recursive method but with no luck.
I thank all the help in advance!
function expand($flat) {
$result = array();
foreach($flat as $key => $val) {
$keyParts = explode("-", $key);
$currentArray = &$result;
for($i=0; $i<count($keyParts)-1; $i++) {
if(!isSet($currentArray[$keyParts[$i]])) {
$currentArray[$keyParts[$i]] = array();
}
$currentArray = &$currentArray[$keyParts[$i]];
}
$currentArray[$keyParts[count($keyParts)-1]] = $val;
}
return $result;
}
Note that the code above is not tested and is given only to illustrate the idea.
The & operator is used for $currentArray to store not the value but the reference to some node in your tree (implemented by multidimensional array), so that changing $currentArray will change $result as well.
Here is an efficient recursive solution:
$foo = array(
"one" => "one_value",
"two-four" => "four_value",
"two-five" => "five_value",
"three-six-seven" => "seven_value"
);
function reverser($the_array) {
$temp = array();
foreach ($the_array as $key => $value) {
if (false != strpos($key, '-')) {
$first = strstr($key, '-', true);
$rest = strstr($key, '-');
if (isset($temp[$first])) {
$temp[$first] = array_merge($temp[$first], reverser(array(substr($rest, 1) => $value)));
} else {
$temp[$first] = reverser(array(substr($rest, 1) => $value));
}
} else {
$temp[$key] = $value;
}
}
return $temp;
}
print_r(reverser($foo));
strstr(___, ___, true) only works with PHP 5.3 or greater, but if this is a problem, there's a simple one-line solution (ask if you'd like it).

create associative array from array

How can I transform
Array1
(
[0] => Some Text
[1] => Some Other Text (+£14.20)
[2] => Text Text (+£26.88)
[3] => Another One (+£68.04)
)
Into associative array like the one below:
Array2
(
[Some Text] => 0 //0 since there is no (+£val) part
[Some Other Text] => 14.20
[Text Text] => Text Text 26.88
[Another One] => 68.04
)
$newArray = array();
foreach( $oldArray as $str ) {
if( preg_match( '/^(.+)\s\(\+£([\d\.]+)\)$/', $str, $matches ) ) {
$newArray[ $matches[1] ] = (double)$matches[2];
} else {
$newArray[ $str ] = 0;
}
}
Something like this should work:
$a2 = array();
foreach ($Array1 as $a1) {
if (strpos($a1, '(') > 0) {
$text = substr($a1, 0, strpos($a1, '('));
$value = substr($a1, strpos($a1, '(')+3, strpos($a1, ')')-1);
} else {
$text = $a1;
$value = 0;
}
$a2[$text] = $value;
}
print_r($a2);
EDIT:
You can do this using explode method as well:
$a2 = array();
foreach ($Array1 as $a1) {
$a1explode = explode("(", $a1, 2);
$text = $a1explode[0];
if ($a1explode[1]) {
$value = substr($a1explode[1],3);
} else {
$value = 0;
}
$a2[$text] = $value;
}
print_r($a2);

How to merge arrays but no numerical keys in fewest lines in php?

$result = array_merge($arr1,$arr2);
I want to exclude numerical values of $arr2,is there an option for this?
Edit after comment:
$arr1 = array('key' => 1);
$arr2 = array('test',1 => 'test', 'key2' => 2);
after processing I need the result to be:
array('key' => 1,'key2' => 2);
Excluding numerical keys
It seems that you want to array_filter your $arr2's keys, first:
function not_numeric( $object ) {
return !is_numeric( $object );
}
$no_numeric_keys = array_filter( array_keys( $arr2 ), not_numeric );
$no_numeric_array = array_intersect_keys( $arr2, $no_numeric_keys );
$result = array_merge( $arr1, $no_numeric_array );
I'm guessing that this would work, after using $result = array_merge($arr1,$arr2);:
foreach ($result as $key => $value) {
if (is_numeric($key)) {
unset($result[$key]);
}
}
Edit:
In as few lines as possible (1) – as requested in the new title:
foreach ($result as $key => $value) { if (is_numeric($key)) { unset($result[$key]); } }
Just loop through each array and test if keys are strings:
$output = array();
foreach($arr1 as $key => $value) {
if(is_string($key)) {
$output[$key] = $value;
}
}
foreach($arr2 as $key => $value) {
if(is_string($key)) {
$output[$key] = $value;
}
}
Edit:
Since you said elegant...
function merge_arrays_string_keys()
{
$output = array();
foreach(func_get_args() as $arr)
{
if(is_array($arr))
{
foreach($arr as $key => $value) {
if(is_string($key) {
$output[$key] = $value;
}
}
}
}
return $output;
}
elegant, huh?
$test = array('test', 1 => 'test', 'key2' => 2, 33, 3 => 33, 'foo' => 'bar');
$test_non_num = array_intersect_key(
$test,
array_flip(
array_diff(
array_keys($test),
array_filter(array_keys($test), 'is_int'))));
print_r($test_non_num); // key2=>2, foo=>bar
Use this code , it will also do the require thing.
<?php
$result = array ( 1,"pavunkumar","bks", 123 , "3" ) ;
array_walk($result,'test_print');
print_r ( $result ) ;
function test_print( $val , $key )
{
global $result;
if ( gettype ( $val ) == 'integer' )
{
unset ( $result[$key] ) ;
}
}
array_diff_ukey($m=$arr2+$arr1,$m,function($k){return is_string($k);})

Categories