i'm trying to remove some array from foreach
example for "result" array :
$result= array (
"1" => array(
"nickname" => "Jow",
"Age"=> "19"
),
"2" => array(
"nickname" => "Rayan",
"Age"=> "25"
),
"3" => array(
"nickname" => "Jinx",
"Age"=> "21"
),
);
i want remove array 1 by nickname
mycode :
foreach ($result as $client => $value){
if ( $value["nickname"] == "Jow"){
unset($result[$client]);
}
echo $value["nickname"].'<p>';
}
Eventually i want The remaining names like Rayan and Jinx
use array_filter ?
$result= array (
"1" => array(
"nickname" => "Jow",
"Age"=> "19"
),
"2" => array(
"nickname" => "Rayan",
"Age"=> "25"
),
"3" => array(
"nickname" => "Jinx",
"Age"=> "21"
),
);
$arr = array_filter($result, 'filter_by_name');
var_dump($arr);exit;
function filter_by_name($value){
if ($value['nickname']=='Jow') {
return false;
} else {
return true;
}
}
Are you looking for something like this?
function removeByNickName($nickName, $array)
{
$temp = array();
foreach($array as $index => $ar)
{
if($array['nickname'] != $nickName) array_push($temp, $ar);
}
return $temp;
}
Related
I have been working on this for long and I got it working as I want but I think there is simpler solution.
So far I got this:
$menu = array(
0 => (object) array(
'cat_id' => 1,
'cat_parent' => 0,
'cat_name' => 'domov',
'cat_href' => 'domov',
'cat_subcategories' => array()
),
1 => (object) array(
'cat_id' => 2,
'cat_parent' => 0,
'cat_name' => 'clanky',
'cat_href' => 'clanky',
'cat_subcategories' => array(
0 => (object) array(
'cat_id' => 9,
'cat_parent' => 2,
'cat_name' => 'apple clanky',
'cat_href' => 'apple',
'cat_subcategories' => array(
0 => (object) array(
'cat_id' => 11,
'cat_parent' => 9,
'cat_name' => 'iphone clanky',
'cat_href' => 'iphone',
'cat_subcategories' => array()
),
1 => (object) array(
'cat_id' => 12,
'cat_parent' => 9,
'cat_name' => 'macbook clanky',
'cat_href' => 'macbook',
'cat_subcategories' => array()
)
)
),
1 => (object) array(
'cat_id' => 10,
'cat_parent' => 2,
'cat_name' => 'microsoft clanky',
'cat_href' => 'microsoft',
'cat_subcategories' => array()
),
)
),
2 => (object) array(
'cat_id' => 3,
'cat_parent' => 0,
'cat_name' => 'produkty',
'cat_href' => 'produkty',
'cat_subcategories' => array()
),
3 => (object) array(
'cat_id' => 4,
'cat_parent' => 0,
'cat_name' => 'vyrobcovia',
'cat_href' => 'vyrobcovia',
'cat_subcategories' =>
array(
0 => (object) array(
'cat_id' => 5,
'cat_parent' => 4,
'cat_name' => 'apple',
'cat_href' => 'apple',
'cat_subcategories' => array(
0 => (object) array(
'cat_id' => 7,
'cat_parent' => 5,
'cat_name' => 'iphone',
'cat_href' => 'iphone',
'cat_subcategories' => array()
),
1 => (object) array(
'cat_id' => 8,
'cat_parent' => 5,
'cat_name' => 'macbook',
'cat_href' => 'macbook',
'cat_subcategories' => array()
)
)
),
1 => (object) array(
'cat_id' => 6,
'cat_parent' => 4,
'cat_name' => 'microsoft',
'cat_href' => 'microsoft',
'cat_subcategories' => array()
),
)
),
);
function generate_menu($menu, $level = 1, $tmp_array = array())
{
foreach($menu as $key => $c)
{
$menu_item = get_menu_elements($c, $level);
$tmp_array = array_replace_recursive($tmp_array, $menu_item);
foreach($c->cat_subcategories as $_key => $_c)
{
$menu_item = get_menu_elements($_c, $level+1);
$tmp_array = array_replace_recursive($tmp_array, $menu_item);
foreach($_c->cat_subcategories as $__key => $__c)
{
$menu_item = get_menu_elements($__c, $level+2);
$tmp_array = array_replace_recursive($tmp_array, $menu_item);
}
}
}
return $tmp_array;
}
function get_menu_elements($c, $level = 1)
{
$level_var = "level_".($level);
$output = array(
$level_var => array()
);
$output[$level_var][$c->cat_id] = array(
'parent' => $c->cat_parent,
'html' => $c->cat_name
);
return $output;
}
In the end I should have multidimensional array with:
array(3) {
["level_1"]=>
array(4) {
[1]=>
array(2) {
["parent"]=>
int(0)
["html"]=>
string(5) "domov"
}
[2]=>
array(2) {
["parent"]=>
int(0)
["html"]=>
string(6) "clanky"
}
[3]=>
array(2) {
["parent"]=>
int(0)
["html"]=>
string(8) "produkty"
}
[4]=>
array(2) {
["parent"]=>
int(0)
["html"]=>
string(10) "vyrobcovia"
}
}
["level_2"]=>
array(4) {
[9]=>
array(2) {
["parent"]=>
int(2)
["html"]=>
string(12) "apple clanky"
}
[10]=>
array(2) {
["parent"]=>
int(2)
["html"]=>
string(16) "microsoft clanky"
}
[5]=>
array(2) {
["parent"]=>
int(4)
["html"]=>
string(5) "apple"
}
[6]=>
array(2) {
["parent"]=>
int(4)
["html"]=>
string(9) "microsoft"
}
}
["level_3"]=>
array(4) {
[11]=>
array(2) {
["parent"]=>
int(9)
["html"]=>
string(13) "iphone clanky"
}
[12]=>
array(2) {
["parent"]=>
int(9)
["html"]=>
string(14) "macbook clanky"
}
[7]=>
array(2) {
["parent"]=>
int(5)
["html"]=>
string(6) "iphone"
}
[8]=>
array(2) {
["parent"]=>
int(5)
["html"]=>
string(7) "macbook"
}
}
}
I want to print multi-level menu recursion. I got it working with this code but in function generate_menu I had to use 3 foreach loops for cat_subcategories. When I used recursion like this:
function generate_menu($menu, $level = 1, $tmp_array = array())
{
foreach($menu as $key => $c)
{
$menu_item = get_menu_elements($c, $level);
$tmp_array = array_replace_recursive($tmp_array, $menu_item);
if (!empty($c->cat_subcategories)) generate_menu($c->cat_subcategories, $level + 1, $tmp_array);
}
return $tmp_array;
}
i got only 'level_1' in output
The output which I am getting now is the same I want I just want to simplify the multiple foreach()
etc. Basicaly
level_1 - first loop of $menu
level_2 - loop of cat_subcategories
level_3 - loop of cat_subcategories for cat_subcategories item
You essentially need to perform a breadth-first traversal in your menu tree. For that I would suggest an iterative function instead of a recursive function, as the latter is more suitable for a depth-first traversal.
Here is the function:
function generate_menu($menu) {
$result = [];
$level = 1;
while (count($menu)) {
$queue = [];
$items = [];
foreach($menu as $cat) {
$items[$cat->cat_id] = [
"parent" => $cat->cat_parent,
"html" => $cat->cat_name
];
$queue = array_merge($queue, $cat->cat_subcategories);
}
$result["level_$level"] = $items;
$level++;
$menu = $queue;
}
return $result;
}
See it run on eval.in.
As this function traverses the top level of the tree, it collects all the children into $queue. Once the top level has been translated into the output (in the level_1 key), that queue will have all second level entries. This then is moved to $menu, and the process is repeated, but now with level_2. This continues until a level is reached where no more entries are found.
I've made some time ago this function. It could help you.
I've got an array where $arr[actual item][parental id]
function getChild($id, $result, $count) {
for( $i = 0; $i < sizeof($result); $i ++) {
if( $result[$i][2] == $id) {
getChild($result[$i][0], $result, $count + 1);
}
}
}
EDIT
In my case, where all the items in the one-dimensional array, but with the hierarchy of n-dimensional array depended on the parental id.
CODE TO PRINT MENU
This code will work for N-number of hierarchy
static function printAllCategoriesAsCheckbox($arr, $d=0){
$htmlString = "";
if (is_array($arr)){
foreach($arr as $category){
$htmlString = $htmlString . '<div><input style="margin-left: ' . 30*$d . 'px;" value="'.$category->id.'" class="category-input" type="checkbox" name="category_id[]">';
$htmlString = $htmlString . ' <label for="category_'.$category->id.'">' . $category->name . '</label></div>';
if (is_array($category['childs'])){
$htmlString = $htmlString . ItemCategory::printAllCategoriesAsCheckbox($category['childs'], $d+1);
}
}
}
return $htmlString;
}
I have it like this:
$data = array(
"City_0" => "London",
"City_1" => "Paris",
"City_2" => "Lisbon",
"City_3" => "Berlin"
);
plus some other data in that same array.
User will select only one of these and what I need is:
Check with preg_match to get all keys that starts with "city_"
find key which has value (it is not empty), take that value
assign it to new key
remove all "city_" keys
add new key to array with the name "chosen_city" which will contain that value
What I tried:
foreach ($data as $key => $value) {
$matches = preg_match('/city_/i', $key);
if ($value != "") {
$newValue = $value;
break;
}
}
$data['chosen_city'] = $newValue;
print_r($data);
This works partially, how can I remove all previous "city_" keys from array in that if statement?
NOTE:
I have other keys in array, and I don't want to remove them as well.
Input array:
$data = array(
"City_0" => "London",
"City_1" => "Paris",
"City_2" => "Lisbon",
"City_3" => "Berlin",
"distance" => "5 km",
"days" => "7",
"tickets" => "2",
"discount" => "10%",
);
Expected output:
$data = array(
"chosen_city" => "Berlin",
"distance" => "5 km",
"days" => "7",
"tickets" => "2",
"discount" => "10%",
);
Thanks.
Please put unset for example code :
$data = array( "City_0" => "London", "City_1" => "Paris", "City_2" => "Lisbon", "City_3" => "Berlin");
foreach($data as $key => $value){
$matches = preg_match('/city_/i', $key);
if($matches && $value != ""){
$newValue = $value;
unset($data[$key]);
}elseif($matches){
unset($data[$key]);
}
}
$data['chosen_city'] = $newValue;
preg_* is somewhat overkill in this instance - you could use strpos and it'd work just as well
However, the question is 'how to I remove the city_* keys', so to do that, just use unset():
foreach($data as $key => $value){
$matches = preg_match('/city_/i', $key);
if($value != ""){
$newValue = $value;
unset($data[$key]); //Remove this item from the array
break;
}
}
$data['chosen_city'] = $newValue;
print_r($data);
$data = array(
"City_0" => "London",
"City_1" => "Paris",
"City_2" => "Lisbon",
"City_3" => "Berlin",
"distance" => "5 km",
"days" => "7",
"tickets" => "2",
"discount" => "10%",
);
$value = 'Berlin';
if (array_search($value, $data)) {
$data['chosen_city'] = $value;
foreach ($data as $key=>$val) {
if (stripos($key, 'city_')===0) {
unset($data[$key]);
}
}
}
result:
array(5) {
'distance' =>
string(4) "5 km"
'days' =>
string(1) "7"
'tickets' =>
string(1) "2"
'discount' =>
string(3) "10%"
'chosen_city' =>
string(6) "Berlin"
}
If you use PHP >=5.6, probably you can use (I didn't tested this code)
$city = array_search($value, $data);
if ($city) {
$data['chosen_city'] = $value;
$data = array_filter($data,function($key,$val){return stripos($key,'city_')===false;},ARRAY_FILTER_USE_BOTH);
}
I have an array of TLDs and prices, and now I want to be able to add a classification i.e. 'Australian','New Zealand','Industry' to the domains but I am having troubles adding the extra dimension.
The array I have is
$domains = array(
'.com.au' => '19.98',
'.melbourne' => '90.00',
'.academy' => '45.00',
'.accountants' => '120.00',
'.ac.nz' => '36.75');
$domains = array(
'.com.au' => array(
'country' => 'Australia',
'sector' => 'Industry',
'price' => '19.98'
),
);
Is this a beginning on what you're looking for ?
Is this code ok for you?
<?php
$domains = array(
'.com.au' => '19.98',
'.melbourne' => '90.00',
'.academy' => '45.00',
'.accountants' => '120.00',
'.ac.nz' => '36.75');
$newDomains = [];
foreach($domains as $key=>$value){
if($key == '.com.au'){
$newDomains[$key]['TLD'] = $value;
$newDomains[$key]['Industry'] = 'blabal';
}else{
$newDomains[$key] = $value;
}
}
echo '<pre>';
var_dump($newDomains);
echo '</pre>';
?>
Or even:
$domains = array(
'.com.au' => '19.98',
'.melbourne' => '90.00',
'.academy' => '45.00',
'.accountants' => '120.00',
'.ac.nz' => '36.75');
$industryArray = array(
'.com.au' => 'blabla'
);
$newDomains = [];
foreach($domains as $key=>$value){
if(isset($industryArray[$key])){
$newDomains[$key]['TLD'] = $value;
$newDomains[$key]['Industry'] = $industryArray[$key];
}else{
$newDomains[$key] = $value;
}
}
echo '<pre>';
var_dump($newDomains);
echo '</pre>';
The result is:
array(5) {
[".com.au"]=>
array(2) {
["TLD"]=>
string(5) "19.98"
["Industry"]=>
string(6) "blabla"
}
[".melbourne"]=>
string(5) "90.00"
[".academy"]=>
string(5) "45.00"
[".accountants"]=>
string(6) "120.00"
[".ac.nz"]=>
string(5) "36.75"
}
I have this following array
$question = array(
"ques_15" => array(
"name" => array(
"0" => "aaa"
)
),
"ques_16" => array(
"name" => array(
"0" => "bbb",
"1" => "ccc"
)
)
);
$i=0;
foreach($question as $k=>$v)
{
echo $question[$k]['name'][$i];
$i++;
}
But my output is only
aaaccc
I am missing the value bbb
You need to iterate the inner 'name' arrays - you could use a nested foreach loop:
$question = array(
"ques_15" => array(
"name" => array(
"0" => "aaa"
)
),
"ques_16" => array(
"name" => array(
"0" => "bbb",
"1" => "ccc"
)
)
);
foreach($question as $quest)
{
foreach($quest['name'] as $val)
{
echo $val;
}
}
you should loop though like so
foreach($question as $q)
{
foreach($q['name'] as $v)
{
echo $v;
}
}
in foreach you don't need a counter $i, it's for while() or for()
you array is two dimensional so you need 2 foreach
Check it out in a functional way.
The shorthand array declaration works only on PHP 5.4+ though, but it still works with your longhand array declaration.
$questions = [
'ques_15' => ['name' => ['aaa']],
'ques_16' => ['name' => ['bbb', 'ccc']]
];
array_map(function($a){
foreach ($a['name'] as $v) echo $v;
}, $questions);
I have the following code. Basically I want to search through the keys of this multidimensional array from top to bottom, but ignore the sub-array with the key specified by $ignoreKey. As you can see by the "array_key_exists" logic, it is currently built for a 1D array.. I tried some examples but having problems (so have left my 1D code as is below).
If all went as planned, I would have "thirtyfromgroup1" echoed.
What would I have to change in the following to achieve this?
$keyCheck = "30";
$ignoreKey = "group2";
if (array_key_exists($keyCheck, $topLevel)) {
echo $topLevel[$keyCheck];
}
$topLevel = array(
"group1" => array
(
"12" => "twelve",
"30" => "thirtyfromgroup1"
),
"group2" => array
(
"14" => "fourteen",
"30" => "thirty"
),
"group3" => array
(
"12" => "twelve",
"26" => "thirty"
),
);
Assuming you just want to ignore keys in the top level of your array, and are just searching the keys in the second level:
$keyCheck = "30";
$ignoreKey = "group2";
$topLevel = array(
"group1" => array(
"12" => "twelve",
"30" => "thirtyfromgroup1"
),
"group2" => array(
"14" => "fourteen",
"30" => "thirty"
),
"group3" => array(
"12" => "twelve",
"26" => "thirty"
),
);
foreach($topLevel as $topKey => $topValue)
{
if ($topKey == $ignoreKey)
continue;
foreach($topValue as $subKey => $subValue)
{
if ($subKey == $keyCheck)
echo $subValue;
}
/* Alternatively:
if (isset($topValue[$keyCheck]))
echo $topValue[$keyCheck];
*/
}