remove complete level of an array - php

im trying to remove a complete level in an array
all the items starting with [1]
i am having no luck with arrays at all. kinda new to me. and reading all the stuff i find is not clear nor example like mine.
heres my code so far. i can remove the submit. but i cant go any farther plus im not sure how to remove all of them in heading,special,item, etc as item [1] - regular caesar salad
thank you for any help you may provide
code
<?php
// version:
$testarray =
Array(
"heading" => Array
(
"0" => 'Salads',
"1" => 'Salads',
"2" => 'Pasta',
),
"special" => Array
(
"0" => '',
"1" => '',
"2" => '',
),
"item" => Array
(
"0" => 'Small Green',
"1" => 'Regular Caesar',
"2" => 'Baked Lasagna',
),
"description" => Array
(
"0" => 'Grape tomatoes, onions, green peppers and cucumbers on the bed of crisp lettuce.',
"1" => 'Classic recipe with romaine lettuce and croutons',
"2" => 'With meat sauce, tomato vegetarian sauce or Alfredo sauce',
),
"price" => Array
(
"0" => 'See Desc',
"1" => '$5.99',
"2" => '$9.69',
),
"notes" => Array
(
"0" => 'Available in Small ($2.99), Regular ($5.99)',
"1" => '',
"2" => '',
),
"submit_val" => 'Submit'
);
echo "testarray";
echo "<pre>";
print_r($testarray);
echo "</pre>";
echo "<hr>";
$removed_data=removeItem($testarray,'Submit');
echo "removed_data";
echo "<pre>";
print_r($removed_data);
echo "</pre>";
echo "<hr>";
die();
// works for submit
function removeItem($look_in_Array, $remove){
foreach($look_in_Array as $key => $value) {
echo $key . ' = ' . $value . '<br>';
if ($value ==$remove) {
echo 'found '.$remove."<br>";
unset($look_in_Array[$key]);
}
}
return $look_in_Array;
}
?>
output desired?:
sample of desired output
$testarray =
Array(
"heading" => Array
(
"0" => 'Salads',
"1" => 'Pasta',
),
"special" => Array
(
"0" => '',
"1" => '',
),
"item" => Array
(
"0" => 'Small Green',
"1" => 'Baked Lasagna',
),
"description" => Array
(
"0" => 'Grape tomatoes, onions, green peppers and cucumbers on the bed of crisp lettuce.',
"1" => 'With meat sauce, tomato vegetarian sauce or Alfredo sauce',
),
"price" => Array
(
"0" => 'See Desc',
"1" => '$9.69',
),
"notes" => Array
(
"0" => 'Available in Small ($2.99), Regular ($5.99)',
"1" => '',
),
"submit_val" => 'Submit'
);

If I understand your question correctly, you're looking to remove any array key [1]. If you're doing this as a function anyway, you can either use unset or declare and return a new array. Using unset() might be what you're looking for, but it is sort of a waste of time in a function because it only passes a local variable. Instead, you may want to pass values onto a new array. Please note that this will retain key values.
function removeItemsRecursive($array,$searchKey) {
/*
** Finds any key value that equals $searchKey
** in a multi-level array and does not pass anything
** equal to $searchKey.
*/
foreach($array AS $key=>$value) { //go through each array and assign [key] => value to $key and $value, respectively
if($key !== $searchKey) //if a key is not equal to the $searchKey (aka 1 for example) then assign something to $newArray
{
if(is_array($value)) //if the value inside of the array is another array (for multilevel arrays)
{
$newArray[$key] = removeItemsRecursive($value,$searchKey); //loop through the function and do this for the next level down.
}
else //if the value inside of the array is scalar
{
$newArray[] = $array[$key]; //the new array is assigned the current value where the array key is not equal to $searchKey.
}
}
}
return $newArray;
}
This will essentially go through each value of the $array and pass that value to $newArray if the $key is not $searchKey, aka removeItemsRecursive($array,1); will return a new array without any values with the key being 1.
Calling the Function
To call the function, simply add:
$array = removeItemsRecursive($testarray,1);
When looking at this new array, you will see the results you're looking for.
echo "<PRE>";
print_r($array);
echo "</PRE>";
//returns the array you're looking for.

http://php.net/manual/en/function.unset.php
use unset function in php. in your case you could just iterate over the array and remove all the element at position 1.

function removeLevel($a, $l) { // $a = entire array, $l = level to remove
$removed = array();
foreach ($a as $inner) { // iterate through the outer array
array_splice($inner,$l,1); // remove the "$l"th element of the $inner array
}
return $a; // return new array with level removed
}
$arrBetter = removeLevel($testarray, 2) will return the array with that level of data removed!

Related

How to change the way php returns the results of a sum with very small values

you will see maybe this problem sounds silly but it has tended me a bit stuck.
You see, I have a function which receives an array, with this array a sum must be made, specifically sum one of its columns (I enter as the third parameter of the function the column I want to sum).This work good. The problem is the way it generates the result. I show you my code:
function sumArray($array, $index, $col) {
$returnArray = []; // temporary container
// sanity checks
if (!is_array($array)) {
return 'error not an array';
}
$firstRow = reset($array);
if (!array_key_exists($index, $firstRow) || !array_key_exists($col, $firstRow)) {
return 'error keys provided not found';
}
foreach ($array as $value) {
if (!isset($returnArray[$value[$index]])) { // initialize
$returnArray[$value[$index]] = [$index => $value[$index], $col => 0];
}
// add value
$returnArray[$value[$index]][$col] += $value[$col]; //here is the sum
}
return $returnArray;
}
$products = array ( //this is the array
array("Id" => "000001",
"Name" => "Cheese",
"Quantity" => "0.00000012",
"Price" => "10"),
array("Id" => "000001",
"Name" => "Cheese",
"Quantity" => "0.00000123",
"Price" => "20"),
array("Id" => "000001",
"Name" => "Cheese",
"Quantity" => "0.00000020",
"Price" => "30"),
array("Id" => "000002",
"Name" => "Ham",
"Quantity" => "0.00000346",
"Price" => "200"),
array("Id" => "000002",
"Name" => "Ham",
"Quantity" => "0.000000998",
"Price" => "100"),
array("Id" => "000003",
"Name" => "Baicon",
"Quantity" => "0.000000492",
"Price" => "900")
);
$summedArray = sumArray($products, 'Name', 'Quantity');
print_r($summedArray);
the result of my sum is a new array. But look at the Quantity column:
Array (
[Cheese] => Array ( [Name] => Cheese [Quantity] => 1.55E-6 )
[Ham] => Array ( [Name] => Ham [Quantity] => 4.458E-6 )
[Baicon] => Array ( [Name] => Baicon [Quantity] => 4.92E-7 )
)
This form: 4.458E-6 I don't like. I would like something like this: 0.000004458
Do you know what I could do to get something like that? A suggestion would be of great help.
It isn't really related to the fact that it's a sum. That's just the default string representation of a small float in PHP. Try this, for example:
$number = 0.000004458;
echo $number; // displays 4.458E-6
The only reason the appearance changes in your output is that those values are strings in your input array, but when you add them together they are converted to floats.
If you want those values to display differently, you'll need to use some kind of formatting function that returns a string.
Assuming you aren't going to be using print_r to display the value in your final product, you can use number_format or printf to display it with however many decimal points you'd like.
foreach ($summedArray as $product => $info) {
echo number_format($info['Quantity'], 9) . PHP_EOL;
// or printf('%.9f', $info['Quantity']) . PHP_EOL;
}

sorting a multi-dimensional array at 2nd level by value php

I have an multi-dimensional array and i want to sort values at 2nd level alphabetically
$shop = array(
"director" => Array
(
"0" => 'Sushil Majumdar',
"1" => 'Jyotirmoy Ray',
"3" => 'Phani Gangopadhyay',
"5" => 'Chitta Bose',
"6" => 'Satyajit Ray',
"7" => 'Ajoy Kar'
),
"producer" => Array
(
"0" => 'Bharat Lokchitram Ltd.',
"1" => 'Lokbani Chitrapratisthan',
"2" => 'Rama Chhayachitra',
"3" => 'Poddar Pictures',
"4" => 'Rama Chhayachitra Ltd.',
"5" => 'Chhayachitra Parishad',
"6" => 'Government of West Bengal',
"7" => 'Bikash Ray Productions',
"8" => 'Epic Films'
)
);
$keys = array('director'=>1);
foreach ($shop as $k => $v){
if(array_key_exists($k, $keys)){
foreach ($v as $ke => $ve){
sort($shop[$k]);
}
}
}
Though it can sort but somehow its not affected in my result
so how can i sort my array values alphabetically in ascending order
Your code snippet is working. But the for each loop you used to iterate over $v does not playing any role in the sorting. So you can remove that one.
Keep like;
foreach ($shop as $k => $v){
if(array_key_exists($k, $keys)){
sort($shop[$k]);
}
}
print_r($shop); //alphabetically sorted values under "director" key
If you print the $shop array, you will find the values under "director" key sorted alphabetically.
You can use the following function to sort your array at 2nd level:
function sortOnKeys($array, array $keys) {
foreach ($array as $k => $v){
if(array_key_exists($k, $keys)){
sort($array[$k]);
}
}
return $array;
}
/* set your keys */
$keys = array('director' => 1, 'producer' => 2);
/* invoke the sorting function */
$sorted = sortOnKeys($shop, $keys);
echo '<pre>';
var_dump($sorted);
echo '</pre>';

count occurrences of values in an associative array in php

Please help me on how to count the occurrences of value in this associative array.
<?php
$employees = array(
1 => array(
'name' => 'Jason Alipala',
'employee_id' => 'G1001-05',
'position' => 1
),
2 => array(
'name' => 'Bryann Revina',
'employee_id' => 'G1009-03',
'position' => 2
),
3 => array(
'name' => 'Jeniel Mangahis',
'employee_id' => 'G1009-04',
'position' => 2
),
4 => array(
'name' => 'Arjay Bussala',
'employee_id' => 'G1009-05',
'position' => 3
),
5 => array(
'name' => 'Ronnel Ines',
'employee_id' => 'G1002-06',
'position' => 3
)
);
?>
This is my code from fake_db.php which I include_once in the index.php. I want to count the occurrences of the same value of 'position'.. e.g. 1 = 1, 2 = 2, 3 = 2
in addition, there is another array named $positions...
$positions = array(
1 => 'TL',
2 => 'Programmer',
3 => 'Converter');
this array is where i compare the 'position' from the $employees array.
any help is appreciated, thank you!
Combination of array_count_values & array_column (PHP 5 >= 5.5.0, PHP 7) should work -
$counts = array_count_values(
array_column($employees, 'position')
);
Output
array(3) {
[1]=>
int(1)
[2]=>
int(2)
[3]=>
int(2)
}
Update
$final = array_filter($counts, function($a) {
return $a >= 2;
});
Output
array(2) {
[2]=>
int(2)
[3]=>
int(2)
}
Demo
array_column — Return the values from a single column of array. array_count_values — Counts all the values of an array.
$positions = array_column($employees, 'position');
print_r(array_count_values($positions));
Output
Array
(
[1] => 1
[2] => 2
[3] => 2
)
Nested loop will do the job. Take an array, keep the key as the actual value and the value in the key as COUNTER of that key.
if the key exists in array that means it has the value just increment else assign 1 to initialize the key with value 1.
e.g. 1=>counter of 1 (occurrences)
$arrayCounter=0;
foreach($employees as $value){
foreach($value as $data){
$position = $data['position'];
if(array_key_exists($position,$arrayCounter)){
$arrayCounter[$position] = arrayCounter[$position]++;
}
else{
$arrayCounter[$position] = 1;
}
}
It is pretty simple. The array $employees is the array you have supplied. You can use this code:
$data = array();
foreach($employees as $employee) {
if(isset($data[$employee['position']])) {
$data[$employee['position']]++;
} else {
$data[$employee['position']] = 1;
}
}
echo "<pre>";
print_r($data);
echo "</pre>";
This gives the output:
Array
(
[1] => 1
[2] => 2
[3] => 2
)
You can use array_count_value() pre-define php function to get your aim.
you can see result here
$total = 0;
foreach($employees as $eNum => $value){
if($aEmployees[$eNum]['position'] == $key){
$total++;
}
}
echo $total;
These codes are inside a function that is called on every iteration of a foreach loop(another array named '$positions')..
$key is a variable that contains value from that foreach loop (the '$positions' array).. this is what I've done, and it works for me. But i don't know if this is the proper way?

PHP multidimensional array search key by value

For example a multidimensional array like an example below
$arr = array(
[H1] => array(
"name" => "A"
"title" => "T1"
)
[H2] => array(
"name" => "B"
"title" => "B1"
)
)
Let's say I would like to search name which equals to A in $arr and if it's matched, the searching should return the key which is H1
How can I do that in php ?
I tried array_keys($arr, "A") but it returns me with an array instead of the key.
This may help -
$arr = array(
'H1' => array(
"name" => "A",
"title" => "T1",
),
'H2' => array(
"name" => "B",
"title" => "B1",
)
);
// Generate a new array with 'keys' and values in 'name'
$new = array_combine(array_keys($arr), array_column($arr, 'name'));
// Search in that new array
$search = array_search('A', $new);
var_dump($search);
Output
string(2) "H1"
Demo
Another simple way would be -
$serach= false;
foreach($arr as $key => $val) {
if($val['name'] == 'A') {
$search= $key;
break;
}
}
var_dump($search);

How to call an array using a string in PHP

I would like to echo a bunch of arrays in numerical order, I tried using WHILE method but lacks the knowledge on how to combine strings to call a variable and get the value inside the array.
$ins1 = array (
"select" => array (
"1" => "1"
),
"note" => array (
"1" => "Message"
)
);
$ins2 = array (
"select" => array (
"1" => "2"
),
"note" => array (
"1" => "Sorry"
)
);
$count = 1;
while($count <= 2){
$ins = '$ins'.$count;
echo $ins["select"][$count] .' '. $ins["note"][$count].'<br>';
$count++;
}
OUTPUT SHOULD BE:
1 Message
2 Sorry
What you're looking for is "Variable variables", through which you can set the variable name dynamically; so to get what you want, change your code as the following:
$count = 1;
while($count <= 2){
$ins = 'ins'.$count;
$var = $$ins; // now your $var is either $ins1 or $ins2 :)
echo $var["select"][1] .' '. $var["note"][1].'<br>';
$count++;
}
The output would be:
1 Message
2 Sorry
You should have combined the two variable, and make life easier:
$ins = [
[//$ins1
"select" => array ("1" => "1"),
"note" => array ("1" => "Message" )
],
[//$ins2
"select" => array ("1" => "2"),
"note" => array ("1" => "Sorry")
]
];
for ($i = 0; $i < count($ins); $i++)
{
echo $ins[$i]["select"][1]." ".$ins[$i]["note"][1]."<br/>";
}
for dynamic name of variables, see other answers.. hope i've helped you.. Cheers! ;)
this will do the trick for you:
$ins1 = array (
"select" => array (
"1" => "1"
),
"note" => array (
"1" => "Message"
)
);
$ins2 = array (
"select" => array (
"1" => "2"
),
"note" => array (
"1" => "Sorry"
)
);
for($i=1; $i<1000; $i++) {
$arr_name = 'ins'.$i;
if(isset($$arr_name)) {
$str = '';
foreach ($$arr_name as $key => $value) {
$str .= $value[1].' ';
}
echo trim($str).'<br/>';
} else {
break;
}
}
Note: I have taken 1000 as a highest possible value, you can change accordingly. like in your case it is 2.

Categories