hi i have following array
$langarr[0][0] = gb
$langarr[0][1] = 1
$langarr[1][0] = de
$langarr[1][1] = 2
$langarr[2][0] = fr
$langarr[2][1] = 3
$langarr[3][0] = it
$langarr[3][1] = 5
Now i wanna search to unset like
if(($keyy = array_search('de', $langarr[][0])) !== false) {
unset($langarr[$keyy]);
}
So i wanna search in the langarr[any][0] and if matched I want to delete the whole dataset like unset($langarr[X]);
How can this be achieved?
$langarr = array();
$langarr[0][0] = "gb";
$langarr[0][1] = "1";
$langarr[1][0] = "de";
$langarr[1][1] = "2";
$langarr[2][0] = "fr";
$langarr[2][1] = "3";
$langarr[3][0] = "it";
$langarr[3][1] = "5";
// Get the key of search array
$value = recursive_array_search("de",$langarr);
// print the key
print_r($value);
// unset the array "de" which has key "1"
unset($langarr[$value]);
// print the resultant array
print_r($langarr);
function recursive_array_search($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
Use array_filter(). It takes a (anonymous) function as the second argument. The function itself receives an array element as its argument. If that function returns false, the array element is removed from the array.
So to take your example, if $needle is 'de', the subarray is removed.
$langarr = array(
array('gb', 1),
array('de', 2),
);
$needle = 'de';
$langarr = array_filter($langarr, function($row) use($needle) {
return ($row[0] != $needle);
});
Online test
<?php
$langarr[0][0] = "gb";
$langarr[0][1] = 1;
$langarr[1][0] = "de";
$langarr[1][1] = 2;
$langarr[2][0] = "fr";
$langarr[2][1] = 3;
$langarr[4][0] = "it";
$langarr[4][1] = 4;
print_r($langarr);
foreach($langarr as $key=>$data){
if($data[0]=='de'){
unset($langarr[$key]);
}
}
print_r($langarr);
?>
Related
I got two nested index arrays, which I want to populate with values using a function.
But on a conditional basis: if this, populate the first array; if that, populate the second array.
Here is what I got:
WORKING, but repetitive
$sectionCounter = 0;
foreach($sections as $section) {
if ($direction === 'up') {
$array1[$sectionCounter][] = 1;
$array1[$sectionCounter][] = 25;
// ...
} else {
$array2[$sectionCounter][] = 1;
$array2[$sectionCounter][] = 25;
// ...
}
$sectionCounter++;
}
PREFERRED (not working yet)
function addElements($temp, $sectionCounter) {
$temp[$sectionCounter][] = 1;
$temp[$sectionCounter][] = 25;
// ...
}
foreach($sections as $section) {
if ($direction === 'up') {
addElements($array1, $sectionCounter);
} else {
addElements($array2, $sectionCounter);
}
$sectionCounter++;
}
You can try another approach instead
$sectionCounter = 0;
$data = [
'up' => $array1,
'other' => $array2
];
foreach($sections as $section) {
$dir = $direction === 'up'? 'up': 'other';
$data[$dir][$sectionCounter][] = 1;
$data[$dir][$sectionCounter][] = 25;
// ...
$sectionCounter++;
}
$array1 = $data['up'];
$array2 = $data['other'];
$arr['animal'][0] = 'Dog';
$arr['animal'][1] = 'Cat';
From that array basically I need to create a function with the array value parameter and then it gives me the array keys.
For example:
find_index('Cat');
Output :
The result is animal, 1
You could probably do something like
function find_index($value) {
foreach ($arr as $index => $index2) {
$exists = array_search($value, $index2);
if ($exists !== false) {
echo "The result is {$index}, {$exists}";
return true;
}
}
return false;
}
Try this:
$arr['animal'][0] = 'Dog';
$arr['animal'][1] = 'Cat';
function find_index($searchVal, $arr){
return array_search($searchVal, $arr);
}
print_r(find_index('Cat', $arr['animal']));
Consider this Array,
$arr['animal'][] = 'Dog';
$arr['animal'][] = 'Cat';
$arr['insects'][] = 'Insect1';
$arr['insects'][] = 'Insect2';
Here is Iterator Method,
$search = 'InsectSub1';
$matches = [];
$arr_array = new RecursiveArrayIterator($arr);
$arr_array_iterator = new RecursiveIteratorIterator($arr_array);
foreach($arr_array_iterator as $key => $value)
{
if($value === $search)
{
$fill = [];
$fill['category'] = $arr_array->key();
$fill['key'] = $arr_array_iterator->key();
$fill['value'] = $value;
$matches[] = $fill;
}
}
if($matches)
{
// One or more Match(es) Found
}
else
{
// Not Found
}
$arr['animal'][] = 'Dog';
$arr['animal'][] = 'Cat';
$arr['insects'][] = 'Insect1';
$arr['insects'][] = 'Insect2';
$search_for = 'Cat';
$search_result = [];
while ($part = each($arr)) {
$found = array_search($search_for, $part['value']);
if(is_int($found)) {
$fill = [ 'key1' => $part['key'], 'key2' => $found ];
$search_result[] = $fill;
}
}
echo 'Found '.count($search_result).' result(s)';
print_r($search_result);
Having some issues parsing my multidimensional php array and removing duplicates. I've spent a good four hours trying to figure out what I'm doing wrong with no luck. If someone could help me out that would wonderful.
Format of multidimensional array:
Array(Array("id"=>?, "step_num"=>?, "desc"=>?))
Example data set:
Array(
[0]=> Array([id]=>1, [step_count]=>1, [desc]=>"Something"),
[1]=> Array([id]=>2, [step_count]=>1, [desc]=>"Something New"),
[2]=> Array([id]=>3, [step_count]=>1, [desc]=>"Something Newest")
)
Here's how I am trying to only have the step_count with the most recent desc by comparing id values: ($subStepsFound has the same format as the above array and $results is an empty array to begin with)
foreach($subStepsFound AS $step){
$found = false;
$removeEntry = false;
$index = 0;
foreach($results AS $key=>$result){
if($step['step_count'] == $result['step_count']){
$found = true;
if($step['id'] > $result['id']){
$removeEntry = true;
}
}
if($removeEntry === true){
$index = $key;
}
}
if($removeEntry === true){
//unset($results[$index]);
$results[$index] = $step;
}
if($found === false){
$results[] = $step;
}
}
Expected output of the resulting array:
Array(
[0]=> Array([id]=>4, [step_count]=>1, [desc]=>"Something Newest")
)
See 1., 2., 3. in comments:
foreach($subStepsFound AS $step){
$found = false;
$removeEntry = false;
$index = 0;
foreach($results AS $key=>$result){
if($step['step_count'] == $result['step_count']){
$found = true;
if($step['id'] > $result['id']){
$removeEntry = true;
}
}
if($removeEntry === true){
$results[$key] = $step; // 2. UP TO HERE
$removeEntry = false; // 3. RESET $removeEntry
}
}
/*
if($removeEntry === true){
//unset($results[$index]);
$results[$index] = $step; // 1. MOVE THIS...
}
*/
if($found === false){
$results[] = $step;
}
}
print_r($results);
Online example: http://sandbox.onlinephpfunctions.com/code/1db78a8c08cbee9d04fe1ca47a6ea359cacdd9e9
/*super_unique: Removes the duplicate sub-steps found*/
function super_unique($array,$key){
$temp_array = array();
foreach ($array as &$v) {
if (!isset($temp_array[$v[$key]])) $temp_array[$v[$key]] =& $v;
}
$array = array_values($temp_array);
return $array;
}
$results = super_unique($subStepsFound, 'step_count');
I'm constructing a gallery which will use the URI to define a set of filter settings. CodeIgniter's ruri_to_assoc() works brilliantly for the majority of my settings as they are as simple as key=>value. However, one value (tags) can contain a number of values that I wish to match against.
As ruri_to_assoc() works off a key/val pairing, how would I set an array to a key in the url? Example:
/days/365/order/oldest/tag/car/tag/red/tag/mustang
At the moment, it looks like I'm going to have to explode the uri_string() and cycle through it myself. Like so:
$test_fil = explode('/',$this->uri->uri_string());
unset($test_fil[0]);
$val = 'key';
foreach($test_fil as $fkey=>$fval){
if($fval=='tags'){
$val = 'tag';
$new_filter['tags'] = '';
}
else{
if($val == 'key'){
$new_filter[$fval] = '';
$val = 'val';
$current_key = $fval;
}
elseif($val == 'val'){
$new_filter[$current_key] = $fval;
$val = 'key';
}
else{
$new_filter['tags'][] = $fval;
}
}
}
Is there something in CI that can do this for me?
We just need to make sure that uri_to_assoc will not override already existing keys when building the array.
In application/core create MY_URI.php :
class MY_URI extends CI_URI
{
protected function _uri_to_assoc($n = 3, $default = array(), $which = 'segment')
{
if ( ! is_numeric($n))
{
return $default;
}
if (isset($this->keyval[$which], $this->keyval[$which][$n]))
{
return $this->keyval[$which][$n];
}
$total_segments = "total_{$which}s";
$segment_array = "{$which}_array";
if ($this->$total_segments() < $n)
{
return (count($default) === 0)
? array()
: array_fill_keys($default, NULL);
}
$segments = array_slice($this->$segment_array(), ($n - 1));
$i = 0;
$lastval = '';
$retval = array();
foreach ($segments as $seg)
{
/*HERE IS THE PART WE TRULY OVERRIDE*/
if ($i % 2)
{
if(is_array($retval[$lastval]))
$retval[$lastval][] = $seg;
else
$retval[$lastval] = $seg;
}
else
{
if(isset($retval[$seg]) && !is_array($retval[$seg]))
{
$tmp = $retval[$seg];
$retval[$seg] = array();
$retval[$seg][] = $tmp;
}
else if(!isset($retval[$seg]))
{
$retval[$seg] = NULL;
$lastval = $seg;
}
}
/*END OVERRIDE*/
$i++;
}
if (count($default) > 0)
{
foreach ($default as $val)
{
if ( ! array_key_exists($val, $retval))
{
$retval[$val] = NULL;
}
}
}
// Cache the array for reuse
isset($this->keyval[$which]) OR $this->keyval[$which] = array();
$this->keyval[$which][$n] = $retval;
return $retval;
}
}
And then in your controller, nothing change :
$myTags = $this->uri->uri_to_assoc();
Here is what I get after testing :
array (size=3)
'days' => string '365' (length=3)
'order' => string 'oldest' (length=6)
'tag' =>
array (size=3)
0 => string 'car' (length=3)
1 => string 'red' (length=3)
2 => string 'mustang' (length=7)
I would like to test if the key of an associative array exist in my $_POST.
my $_POST is like that:
$_POST["balle"]["x"] = 5;
$_POST["balle"]["y"] = 5;
$_POST["balle"]["z"] = 5;
or like that by example:
$_POST["p1"][1]["vit"] = 7;
$_POST["p1"][1]["angle"] = 32;
$_POST["p2"][2]["vit"] = 17;
$_POST["p2"][2]["angle"] = 2;
the values don't matter but I must check how are my $_POST keys.
I don't understand how i can test recursivly that because the $_POST can change and have differents forms.
I have try this:
function Check_post($new, $arr)
{
echo "Init<br/>";
$res = true;
if (is_array($new))
{
foreach ($new as $key => $value)
{
if (!in_array($key, $arr))
{
echo "Fail $key";
print_r($arr);
return (false);
}
$res = $res & Check_post($new[$key], $arr[$key]);
}
}
else
$res = in_array($new, $arr);
echo "MY RESULT";
var_dump($res);
return ($res);
}
$b = array();
$b["balle"] = array("x", "y", "z");
$post = array();
$post["balle"] = array();
$post["balle"]["x"] = 50;
$post["balle"]["y"] = 50;
$post["balle"]["z"] = 50;
echo "<pre>";
print_r($b);
echo "</pre><pre>";
print_r($post);
echo "</pre>";
Check_post($b, $post);
but i got "Fail balle". my $post variable is to simulate the real $_POST and for make it easier to test.
EDIT:
The function should work like that:
1) test if "balle" exist in $post
2) "balle" exist so recursive call
3) test if "x" exist in $post["balle"](recursive)
4) test if "y" exist in $post["balle"](recursive)
5) test if "z" exist in $post["balle"](recursive)
6) all existe so $res = true
EDIT:
I finaly editet the whole function:
function Check_post($needle, $haystack)
{
if(is_array($needle)){
foreach ($needle as $key => $element){
$result = true;
if($result = (array_key_exists($key, $haystack) || array_key_exists($element, $haystack))){
$key = (isset($haystack[$key]) ? $key : $element);
if(is_array($haystack[$key]))
$result = Check_post($element, $haystack[$key]);
}
if(!$result){
return false;
}
}
return $result;
}else {
return array_key_exists($needle, $haystack);
}
}
Now it should work as you want it
Example:
$_POST["balle"]["x"] = 5;
$_POST["balle"]["y"] = 5;
$_POST["balle"]["z"] = 5;
$b = array();
$b["balle"] = array("x", "y", "z");
var_dump(Check_post($b, $_POST)); //returns true
$b["balle"] = array("x", "y", "z", "b");
var_dump(Check_post($b, $_POST)); //returns false
The in_array function you're using checks if $key is contained in $arr as a value. If I got you right, you want to check if there is the same key in $arr instead. Use array_key_exists($key, $arr) for this.
Try this
$_POST["p1"][1]["vit"] = 7;
$_POST["p1"][1]["angle"] = 32;
$_POST["p2"][2]["vit"] = 17;
$_POST["p2"][2]["angle"] = 2;
$needle = "2";
$samp = Check_post($_POST,$needle);
echo $samp;
function Check_post($array,$needle)
{
if(is_array($array))
{
foreach($array as $key=>$value)
{
if($key == $needle)
{
echo $key." key exists ";
}
else
{
if(is_array($value))
{
check_post($value,$needle);
}
}
}
}
}
Demo