Filter a multidemensional array - php

I have an array that looks kinda like this:
array(1) { ["Special"]=> array(4) { [0]=> array(2) { ["ID"]=> int(1) ["Visitors"]=> int(2) } [1]=> array(2) { ["ID"]=> int(4) ["Visitors"]=> int(5) } [2]=> array(2) { ["ID"]=> int(169) ["Visitors"]=> int(0) } } }
How can I filter it by 'ID' value, so the result would be looking like this (if I need to get arrays with ID = 4):
array(1) { ["Special"]=> array(4) { [1]=> array(2) { ["ID"]=> int(4) ["Visitors"]=> int(5) } } }
I tried to use that function, but it doesn't return what I need:
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; }

You can use array_filter to do this:
$result = array(
"Special" => array_filter($array["Special"], function($element) {
return $element["ID"] == 4;
})
);

Related

how to use explode for an array of objects

I have an array like that:
array(5) {
["code"]=>
int(1)
["messageError"]=>
string(27) "La typologie est incorrecte"
["model"]=>
string(3) "lot"
["grp_regles"]=>
array(1) {
[0]=>
array(1) {
[0]=>
array(3) {
["champ"]=>
string(21) "lot_surface_habitable"
["comparaison"]=>
string(7) "between"
["valeurAttendue"]=>
array(2) {
[0]=>
int(16)
[1]=>
int(40)
}
}
}
}
["prerequis"]=>
array(2) {
[0]=>
array(3) {
["champ"]=>
string(6) "typ_id"
["comparaison"]=>
string(1) "="
["valeurAttendue"]=>
int(1)
}
[1]=>
array(3) {
["champ"]=>
string(22) "tranche.fus.fup.fup_id"
["comparaison"]=>
string(1) "="
["valeurAttendue"]=>
int(1)
}
}
}
I want to do a foreach in "prerequis":
$modelRetrieve = $this->retrieveModel($model);
$modelFind = $modelRetrieve::find($id);
$arrayError=[];
$query = '';
$path = storage_path() . "/json/controle.json";
$json = file_get_contents($path);
foreach (json_decode($json,true) as $key => $value) {
$test = true;
var_dump($value);
if($value['model'] === $model ){
foreach ($value['prerequis'] as $key => $value2) {
if( $test && $modelFind[$value2['champ']] == (int)$value2["valeurAttendue"] )
{
$test = true;
}
}
}
}
I need in second foreach to use in $value2['champ'] where $value2['champ'] is "tranche.fus.fup_id. So I need to explode that to have ['tranche']['fus']['fup_id'].
How to use explode with that ?
thanks everyone :)
you can use laravel data_get helper:
data_get($value2, $value2['champ'])
To nest the $segments of the string starting with the innermost item of the result, we have to array_reverse() the $segments so we can loop over it and wrap each iteration's result with another array level in the next iteration until we looped through the whole $segments array.
$exploded = array_reduce(array_reverse(explode('.', $value2['champ'])), function($res, $segment) {
return [ $segment => $res ];
}, []);

notice trying to access array offset on value of type null wordpress plugins

i must update my website to the last version of php 7.4 after that i find this notice in some plugins
**> Notice: Trying to access array offset on value of type null in
C:\projets\htdocs\mapsport\wp-content\plugins\ekit-megamenu\library\scss\scss.inc.php
on line 1753**
protected function sortArgs($prototype, $args) {
$keyArgs = array();
$posArgs = array();
foreach ($args as $arg) {
list($key, $value) = $arg;
$key = $key[1]; // line 1753
if (empty($key)) {
$posArgs[] = $value;
} else {
$keyArgs[$key] = $value;
}
}
if (!isset($prototype)) return $posArgs;
$finalArgs = array();
foreach ($prototype as $i => $names) {
if (isset($posArgs[$i])) {
$finalArgs[] = $posArgs[$i];
continue;
}
$set = false;
foreach ((array)$names as $name) {
if (isset($keyArgs[$name])) {
$finalArgs[] = $keyArgs[$name];
$set = true;
break;
}
}
if (!$set) {
$finalArgs[] = null;
}
}
return $finalArgs;
}
how can i change the code without change my php version ?
the result after add var_dump($args); before the foreach Suggested by #Ro Achterberg
array(2) { [0]=> array(3) { [0]=> NULL [1]=> array(2) { [0]=>
string(3) "var" [1]=> string(23) "ekit-menu-simple__white" } [2]=>
bool(false) } [1]=> array(3) { [0]=> NULL [1]=> array(3) { [0]=>
string(6) "number" [1]=> string(3) "6.5" [2]=> string(1) "%" } [2]=>
bool(false) } }
On line 1752 the value of $key is NULL. It doesn't get any value. So can you please try $key = isset( $key[1] ) ? $key[1] : '';?

Function $_POST return value from array parameter

I had this response from method post
array(7) {
["enable"]=>
array(2) {
[0]=>
string(2) "on"
[1]=>
string(2) "on"
}
["value"]=>
array(2) {
[0]=>
string(8) "R$ 10,00"
[1]=>
string(8) "R$ 10,00"
}
["zip_code"]=>
array(2) {
[0]=>
string(9) "57200-970"
[1]=>
string(9) "57200-990"
}
["address"]=>
array(2) {
[0]=>
string(28) "Avenida Floriano Peixoto"
[1]=>
string(33) "Povoado Tabuleiro dos Negros"
}
["neighborhood"]=>
array(2) {
[0]=>
string(6) "Centro"
[1]=>
string(4) "Bairro Vermelho"
}
["city"]=>
array(2) {
[0]=>
string(6) "Penedo"
[1]=>
string(6) "Penedo"
}
["state"]=>
array(2) {
[0]=>
string(2) "AL"
[1]=>
string(2) "AL"
}
}
I need first use the foreach to get the $_POST['active'] and get value from another arrays index
foreach (Request::post('enable') as $k => $v) {
print Request::post(array("zip_code", $k)) . "\n";
// I hope same result of $_POST['zip_code'][$k]
}
the real problem is my function
public static function post($key, $clean = false) {
$result = is_array($key) ? array_search($key, $_POST) : $_POST[$key];
if (!empty($result)) {
return ($clean) ? trim(strip_tags($result)) : $result;
}
return NULL;
}
if param key is an array get value from this key array
for example $_POST['a']['b']['c']
[EDIT]
I improve the function, thanks #mickmackusa
public static function post($key, $clean = false) {
$focus = $_POST;
if (is_array($key)) {
foreach ($key as $k) {
if (!isset($focus[$k])) {
return NULL;
}
$focus = $focus[$k];
if (!is_array($focus)) {
$result = $focus;
}
}
} else {
$result = empty($focus[$key]) ? NULL : $focus[$key];
}
return ($clean ? trim(strip_tags($result)) : $result);
}
I think line1 inside post() is fouling things up. Depending on $key's type, you are declaring $result's value as a key or a value. But then seemingly treating both possibilities as a value in the next condition and returning it.
public static function post($key, $clean=false) {
$result = is_array($key) ? array_search($key, $_POST) : $_POST[$key];
// if $key is an array, then $result is the key of the found value within $POST or FALSE if not found
// if $key is not an array, then $result is the value of $_POST[$key]
if (!empty($result)) {
return ($clean) ? trim(strip_tags($result)) : $result;
}
return NULL;
}
The !empty condition is checking for NOT falsey values in $result.
See all falsey values # empty() manual, including 0 which can be a totally legitimate index/key, and more.
Instead, I think you want to use:
public static function post($key,$clean=false){
$focus=$_POST;
foreach($key as $k){
if(!isset($focus[$k])){
return NULL;
}else{
$focus=$focus[$k];
if(!is_array($focus)){
$result=$focus;
}
}
}
return ($clean?trim(strip_tags($result)):$result);
}

How to iterate through elements of an array up until its seventh

I have a function that iterates throughout an array
function ($data)
{
$path = $data->data->data->clicks;
foreach ($path as $key => $item){
if ($key >= 0) {
$array[] = $item->clicks;
}
}
return json_encode($array);
}
I try to make it iterate up until its seventh key, I have written an if statement but I am quite new to this and I don't know how to do this.
If it help the array structure look like this:
["data"]=>
object(stdClass)#212 (3) {
["status_code"]=>
int(200)
["data"]=>
object(stdClass)#211 (3) {
["days"]=>
int(30)
["total_clicks"]=>
int(6)
["clicks"]=>
array(30) {
[0]=>
object(stdClass)#215 (2) {
["clicks"]=>
int(0)
["day_start"]=>
int(1466395200)
}
[1]=>
object(stdClass)#216 (2) {
["clicks"]=>
int(0)
["day_start"]=>
int(1466308800)
}
[2]=>
object(stdClass)#217 (2) {
["clicks"]=>
int(0)
["day_start"]=>
int(1466222400)
}
Just add a variable that counts up and break when it's greater than 7
$num_loops = 0;
foreach ($path as $key => $item){
$num_loops++;
if($num_loops > 7) break;
if ($key >= 0) {
$array[] = $item->clicks;
}
}
The short way by using array_map and array_slice functions(no loops, no if conditions):
$path = $data->data->data->clicks;
$clicks = array_map(function($o){
return $o->clicks;
}, array_slice($path, 0, 7));

Remove all elements from array where integers are lower than 3

I need to delete all elements where FacetValueCount is lower than 3.
How can I do this?
This is my array: Array name is $farben
array(8) {
[0]=>
array(2) {
["FacetValueName"]=>
string(4) "Blau"
["FacetValueCount"]=>
int(5)
}
[1]=>
array(2) {
["FacetValueName"]=>
string(7) "Schwarz"
["FacetValueCount"]=>
int(3)
}
[2]=>
array(2) {
["FacetValueName"]=>
string(4) "blue"
["FacetValueCount"]=>
int(2)
}
[3]=>
array(2) {
["FacetValueName"]=>
string(4) "Grau"
["FacetValueCount"]=>
int(1)
}
}
<?php
$farben = ARRAY();
$farben[] = array('FacetValueName'=>'Blau', 'FacetValueCount' => 5);
$farben[] = array('FacetValueName'=>'Schwarz', 'FacetValueCount' => 3);
$farben[] = array('FacetValueName'=>'blue', 'FacetValueCount' => 2);
$farben[] = array('FacetValueName'=>'Grau', 'FacetValueCount' => 1);
print '<pre>'; var_dump($farben); print '</pre>';
foreach ($farben AS $key => $row) {
if ($row['FacetValueCount'] < 3) { unset($farben[$key]); }
}
print '<pre>'; var_dump($farben); print '</pre>';
?>
try this...
$farben = array_filter($farben, function($row) {
if($row["FacetValueCount"] > 3) {
return $row;
}
});

Categories