PHP one array with and without explicit keys - php

I'm trying to figure out a better/cleaner way to have something like this in PHP:
// This will be parsed as the only argument in a function...
$params = array('Name', 'Age', 'Mail' => 'some#mail.com');
"Name" and "Age" are values with automatic keys (0 and 1, eg.), and "Mail" is a key with "some#mail.com" value:
[0] => 'Name',
[1] => 'Age',
['Mail'] => 'some#mail.com'
When running through it in a foreach loop, to have "Name" and "Age" as the actual parameters I'm using this:
foreach ($params as $k => $i) {
// This is the ugly part!
if (is_int($k)) {
$k = $i;
$i = false;
}
// To do something like this, for example...
$out = "";
if ($i) {
$out .= "<p>$k</p>\n";
} else {
$out .= "<p>$k<p>\n";
}
}
That will return something like this:
<p>Name</p>
<p>Age</p>
<p>Mail</p>
Is there a better way to do it?
Thanks in advance.
Edit #1: Elaborating the question: is there a clean PHP way to distinguish elements that have explicitly informed keys from the ones that have not in the same array?

You are right about the ugly part. It should be better when you use keys for all elements, and decide on the key name whether of not to use the mail link:
$params = array('name'=>'Name', 'age'=>'Age', 'mail'=>'some#mail.com');
foreach ($params as $k => $i) {
$out .= ($k == 'mail') ? '$k' : $k;
}

Why not just give name and age a key?
Or better yet, if you know that the params array will always be in this format, ditch the loop all together:
echo '<p>'.$params[0].'</p>';
echo '<p>'.$params[1].'</p>';
echo '<p>Mail</p>;

if (!is_int($k)) {
$out .= "<p>$k</p>\n";
} else {
$out .= "<p>$i<p>\n";
}

I found 2 solution for what I wanted:
1 - Sticking to the original approach, I could pass the arguments as follows:
my_function(['Name', 'Age', ['Mail' => 'a#mail.com']]);
or...
my_function(array('Name', 'Age', array('Mail' => 'a#mail.com')));
Using "is_array()" later on to distinguish the parameter's type:
if (is_array($i)) {
$p = current($i);
$c = key($i);
$out .= "<p>$c</p>\n";
} else {
$out .= "<p>$i<p>\n";
}
2 - But, changing my original paradigm, I found another option to parse a undefined number of arguments: the function "func_get_args()". My function would be called like this:
my_function('Name', 'Age', ['Mail' => 'a#mail.com']);
or...
my_function('Name', 'Age', array('Mail' => 'a#mail.com'));
Here is an example to create table rows:
function add_table_row() {
$args = func_get_args(); // returns an array of arguments...
$o = "<tr>\n";
foreach ($args as $value) {
if (is_array($value)) { // If the argument is an array...
$cellcont = key($value); // The contents is the key...
$param = current($value); // And the parameter is the value...
$o .= "<td $param>$cellcont</td>\n";
} else {
$o .= "<td>$value</td>\n";
}
}
$o .= "</tr>\n";
return $o;
}
Bottom line, both solutions uses "is_array" the same way, but the second one looks more clear, IMO.

Related

Convert a nested Array to Scalar and then reconvert the scalar to nested array

I have an array that looks like this.
$array = [
0 => 'abc',
1 => [
0 => 'def',
1 => 'ghi'
],
'assoc1' => [
'nassoc' => 'jkl',
'nassoc2' => 'mno',
'nassoc3' => '',
'nassoc4' => false
]
];
The $array can have numeric keys or be an assoc array or a mixed one. The level of nesting is not known. Also the values of the array can also be bool or null or an empty string ''
I need to able to convert this into a scalar array with key value pairs. And then later reconvert it back to the exact same array.
So the scalar array could look like
$arrayScalar = [
'0' => 'abc',
'1[0]' => 'def',
'1[1]' => 'ghi',
'assoc1[nassoc]' => 'jkl',
'assoc1[nassoc2]' => 'mno',
'assoc1[nassoc3]' => '',
'assoc1[nassoc4]' => false
];
And then later be able to get back to the initial $array.
I wrote a parser and it does not currently handle bool values correctly.
I have a feeling this is at best a super hacky method to do what I am after. Also I have been able to test it only so much.
function flattenNestedArraysRecursively($nestedArray, $parent = '', &$flattened = [])
{
$keys = array_keys($nestedArray);
if (empty($keys)) {
$flattened[$parent] = 'emptyarray';
} else {
foreach ($keys as $value) {
if (is_array($nestedArray[$value])) {
$reqParent = (!empty($parent)) ? $parent . '|!|' . $value : $value;
$this->flattenNestedArraysRecursively($nestedArray[$value], $reqParent, $flattened);
} else {
$reqKey = (!empty($parent)) ? $parent . '|!|' . $value : $value;
$flattened[$reqKey] = $nestedArray[$value];
}
}
}
return $flattened;
}
function reCreateFlattenedArray($flatArray): array
{
$arr = [];
foreach ($flatArray as $key => $value) {
$keys = explode('|!|', $key);
$arr = $this->reCreateArrayRecursiveWorker($keys, $value, $arr);
}
return $arr;
}
function reCreateArrayRecursiveWorker($keys, $value, $existingArr)
{
//Outside to Inside
$keyCur = array_shift($keys);
//Check if keyCur Exists in the existingArray
if (key_exists($keyCur, $existingArr)) {
// Check if we have reached the deepest level
if (empty($keys)) {
//Return the Key => value mapping
$existingArr[$keyCur] = $value;
return $existingArr;
} else {
// If not then continue to go deeper while appending deeper levels values to current key
$existingArr[$keyCur] = $this->reCreateArrayRecursiveWorker($keys, $value, $existingArr[$keyCur]);
return $existingArr;
}
} else {
// If Key does not exists in current Array
// Check deepest
if (empty($keys)) {
//Return the Key => value mapping
$existingArr[$keyCur] = $value;
return $existingArr;
} else {
// Add the key
$existingArr[$keyCur] = $this->reCreateArrayRecursiveWorker($keys, $value, []);
return $existingArr;
}
}
}
Is there a better more elegant way of doing this, maybe http_build_query or something else I am not aware of.
Sandbox link -> http://sandbox.onlinephpfunctions.com/code/50b3890e5bdc515bc145eda0a1b34c29eefadcca
Flattening:
Your approach towards recursion is correct. I think we can make it more simpler.
We loop over the array. if the value is an array in itself, we recursively make a call to this new child subarray.
This way, we visit each key and each value. Now, we are only left to manage the keys to assign them when adding to our final resultant array, say $arrayScalar.
For this, we make a new function parameter which takes the parent key into account when assigning. That's it.
Snippet:
$arrayScalar = [];
function flatten($array,&$arrayScalar,$parent_key){
foreach($array as $key => $value){
$curr_key = empty($parent_key) ? $key : $parent_key . '[' . $key . ']';
if(is_array($value)){
flatten($value,$arrayScalar,$curr_key);
}else{
$arrayScalar[$curr_key] = $value;
}
}
}
flatten($array,$arrayScalar,'');
var_export($arrayScalar);
Demo: http://sandbox.onlinephpfunctions.com/code/1e3092e9e163330f43d495cc9d4acb672289a987
Unflattening:
This one is a little tricky.
You might have already noticed that the keys in the flattened array are of the form key1[key2][key3][key4] etc.
So, we collect all these individually in a new array, say $split_key. It might look like this.
array (
'key1',
'key2',
'key3',
'key4',
)
To achieve the above, we do a basic string parsing and added in-between keys to the array whenever we reach the end of the key string or [ or ].
Next, to add them to our final resultant array, we loop over the collected keys and check if they are set in our final array. If not so, set them. We now pass child array reference to our temporary variable $temp. This is to edit the same copy of the array. In the end, we return the result.
Snippet:
<?php
function unflatten($arrayScalar){
$result = [];
foreach($arrayScalar as $key => $value){
if(is_int($key)) $key = strval($key);
$split_key = [];
$key_len = strlen($key);
$curr = '';
// collect them as individual keys
for($i = 0; $i < $key_len; ++$i){
if($key[ $i ] == '[' || $key[ $i ] == ']'){
if(strlen($curr) === 0) continue;
$split_key[] = $curr;
$curr = '';
}else{
$curr .= $key[ $i ];
}
if($i === $key_len - 1 && strlen($curr) > 0){
$split_key[] = $curr;
}
}
// collecting them ends
//add them to our resultant array.
$temp = &$result;
foreach($split_key as $sk){
if(!isset($temp[ $sk ])){
$temp[ $sk ] = [];
}
$temp = &$temp[$sk];
}
$temp = $value;
}
return $result;
}
var_export(unflatten($arrayScalar));
Demo: http://sandbox.onlinephpfunctions.com/code/66136a699c3c5285eed3d3350ed4faa5bbce4b76

Removing an associated key/value pair from array (nested)

I have two function to add remove parameters to the query string. The "add_query_params" (thanks to this forum) is working nicely and I can now add multiple tags to the query string of the same type.
For example
http://example.com?tags[]=flowers&tags[]=shrubs&category[]=garden
As you can see, I can add multiple of the same parameters, I am also querying these nicely using queryfilters.
However my newest problem, is simply removing a single tag type without affecting the rest of the query string. I will then rebuild the query without the deleted tag.
Someone kindly yesterday helped me to to a point but this removes ALL tag key values, not just the specified tag.
So if I was to delete say $tags[]shrubs from the above URL it would actually delete BOTH tag[]shrubs AND $tags[]flowers.
This obviously isn't very intuitive for a filter system I am devising. What I would like to know is how to remove just the single key value pair and leave the other keys pairs intact.
Here is my helper function
//Accept a param array which passthrough through tag type eg category/tag and value
function remove_query_params(array $params = [])
{
//Set to array
$existingParams = [];
$existingParams = request()->query();
foreach($params as $key=>$value){
if (isset($existingParams[$value])) {
unset($existingParams[$value]);
}
}
$query = http_build_query($existingParams);
return url()->current() . '?' . $query;
}
//Need to return: user removes tag from filter in blade, URL recontructs without the passed through tag value
//Before
//http://example.com?tags[]=flowers&tags[]=shrubs&category[]=garden
//After
//http://example.com?tags[]=flowers&category[]=garden
This does not work, if I change $value to $key then it will will, but it will remove all keys of the same type, not the behaviour I would like.
I activate this behaviour via a call in the blade template, this forms a href
//Pass through parameter type and parameter value
{{remove_query_params(['category' => $category->id]) }}
Has anybody got any pointers as to where I go next?#
Thanks and fingers crossed I am not far off :)
Adam
I hope this solution will help you:
<?php
function remove_query_params(array $params = [])
{
//Set to array
$existingParams = [
'tags' => [
'aaaa',
'bbbb'
],
'category' => 'ccc'
];
// go trough all parameters
foreach ($existingParams as $key1 => $value1) {
// go to the parameters, which need to be deleted
foreach ($params as $key2 => $value2) {
// only if the keys equals, do something
if ($key1 === $key2) {
// if the param is an array
if (is_array($value1)) {
foreach ($value1 as $k => $v) {
// if the elements to delete are an array
if (is_array($value2)) {
foreach ($value2 as $b => $r) {
if ($v == $r) {
unset($existingParams[$key1][$k]);
}
}
} else {
if ($v == $value2) {
unset($existingParams[$key1][$k]);
}
}
}
} else {
if (isset($existingParams[$key2])) {
unset($existingParams[$key2]);
}
}
}
}
}
$query = http_build_query($existingParams);
return $query;
}
echo remove_query_params(['tags' => 'aaaa']);
echo "\n";
echo remove_query_params(['tags' => ['aaaa', 'bbbb']]);
echo "\n";
echo remove_query_params(['category' => 'ccc']);
echo "\n";
tags is not an associated array. It is just a list of strings. Also, look at the value of $existingParams = request()->query(); It is not the tags array. It is an object that contains it. That is why when you use $key it works but deletes everything because $key is tags. So, in your check $existingParams['tags'] should be checked for the shrubs value. in_array is what you are looking in this case.
Hope this will solve your problem.I just provided the core function to get the things done in a way
$query = "tags[]=flowers&tags[]=shrubs&category[]=garden";
echo (remove_query_params( [ 'tags' => 'shrubs' ], $query ));
function remove_query_params(array $params = [], $query )
{
parse_str( $query, $existingParams );
$existing_keys = array_keys( $existingParams);
foreach($params as $key=>$value){
if( in_array( $key, $existing_keys ) ){
foreach ($existingParams[$key] as $param_key => $param_value) {
if( $param_value == $value ){
unset( $existingParams[$key][$param_key] );
}
}
}
}
$query = http_build_query($existingParams);
return $query;
}

Echo selected values from an associate array

i dont want to echo the last two values in an associative array, couldn's figure it out, please help.
foreach($_POST as $key => $value){
echo $value;
}
This echoes all the values, i want to echo all but the last 2.
Just count the loops and dont print the value in the last two loops.
$i = 0;
foreach($_POST as $key => $value) {
$i++;
if($i != count($_POST) && $i != count($_POST)-1) {
echo $value;
}
}
It should work to slice the array before you loop it.
<?php
$newArray = array_slice( $_POST, 0, count($_POST)-2);
foreach( $newArray AS $key => $value ) {
echo $value;
}
If you want to keep your $key value, then set the 4th parameter to true to "preserve keys":
http://php.net/manual/en/function.array-slice.php
Maybe this is just an exercise, but I do want to note, in addition, that relying on the exact order of your POST'd elements sounds like a bad design idea that could lead to future problems.
I'd rather do this:
$a = array('a' => 'q','s' => 'w','d' => 'e','f' => 'r');
$arr_count = count($a) - 2;
$i = 1;
foreach($a as $k => $val){
echo $k.' - '.$val.PHP_EOL;
if ($i == $arr_count) break;
$i++;
}
Another alternative solution:
<?php
$tot=count($_POST)-2;
while ($tot--) {
// you can also retrieve the key using key($_POST);
echo current($_POST);
next($_POST);
}

PHP Can't get the right format for array

I got stuck somehow on the following problem:
What I want to achieve is to merge the following arrays based on key :
{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}
Which needs to output like this:
[{"item_header":"Entities"},
{"list_items" :
[{"submenu_id":"Parents","submenu_label":"parents"},
{"submenu_id":"Insurers","submenu_label":"insurers"}]
}]
[{"item_header":"Users"},
{"list_items" :
[{"submenu_id":"New roles","submenu_label":"newrole"}
{"submenu_id":"User - roles","submenu_label":"user_roles"}
{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}]
}]
[{"item_header":"Accounting"},
{"list_items" :
[{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}]
}]
I have been trying all kinds of things for the last two hours, but each attempt returned a different format as the one required and thus failed miserably. Somehow, I couldn't figure it out.
Do you have a construction in mind to get this job done?
I would be very interested to hear your approach on the matter.
Thanks.
$input = array(
'{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}}',
'{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}}',
'{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}}',
'{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}}',
'{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}}',
'{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}',
);
$input = array_map(function ($e) { return json_decode($e, true); }, $input);
$result = array();
$indexMap = array();
foreach ($input as $index => $values) {
foreach ($values as $k => $value) {
$index = isset($indexMap[$k]) ? $indexMap[$k] : $index;
if (!isset($result[$index]['item_header'])) {
$result[$index]['item_header'] = $k;
$indexMap[$k] = $index;
}
$result[$index]['list_items'][] = $value;
}
}
echo json_encode($result);
Here you are!
In this case, first I added all arrays into one array for processing.
I thought they are in same array first, but now I realize they aren't.
Just make an empty $array=[] then and then add them all in $array[]=$a1, $array[]=$a2, etc...
$array = '[{"Entities":{"submenu_id":"Parents","submenu_label":"parents"}},
{"Entities":{"submenu_id":"Insurers","submenu_label":"insurers"}},
{"Users":{"submenu_id":"New roles","submenu_label":"newrole"}},
{"Users":{"submenu_id":"User - roles","submenu_label":"user_roles"}},
{"Users":{"submenu_id":"Roles - permissions","submenu_label":"roles_permissions"}},
{"Accounting":{"submenu_id":"Input accounting data","submenu_label":"new_accounting"}}]';
$array = json_decode($array, true);
$intermediate = []; // 1st step
foreach($array as $a)
{
$keys = array_keys($a);
$key = $keys[0]; // say, "Entities" or "Users"
$intermediate[$key] []= $a[$key];
}
$result = []; // 2nd step
foreach($intermediate as $key=>$a)
{
$entry = ["item_header" => $key, "list_items" => [] ];
foreach($a as $item) $entry["list_items"] []= $item;
$result []= $entry;
}
print_r($result);
I would prefer an OO approach for that.
First an object for the list_item:
{"submenu_id":"Parents","submenu_label":"parents"}
Second an object for the item_header:
{"item_header":"Entities", "list_items" : <array of list_item> }
Last an object or an array for all:
{ "Menus: <array of item_header> }
And the according getter/setter etc.
The following code will give you the requisite array over which you can iterate to get the desired output.
$final_array = array();
foreach($array as $value) { //assuming that the original arrays are stored inside another array. You can replace the iterator over the array to an iterator over input from file
$key = /*Extract the key from the string ($value)*/
$existing_array_for_key = $final_array[$key];
if(!array_key_exists ($key , $final_array)) {
$existing_array_for_key = array();
}
$existing_array_for_key[count($existing_array_for_key)+1] = /*Extract value from the String ($value)*/
$final_array[$key] = $existing_array_for_key;
}

How can I easily remove the last comma from an array?

Let's say I have this:
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
foreach($array as $i=>$k)
{
echo $i.'-'.$k.',';
}
echoes "john-doe,foe-bar,oh-yeah,"
How do I get rid of the last comma?
Alternatively you can use the rtrim function as:
$result = '';
foreach($array as $i=>$k) {
$result .= $i.'-'.$k.',';
}
$result = rtrim($result,',');
echo $result;
I dislike all previous recipes.
Php is not C and has higher-level ways to deal with this particular problem.
I will begin from the point where you have an array like this:
$array = array('john-doe', 'foe-bar', 'oh-yeah');
You can build such an array from the initial one using a loop or array_map() function. Note that I'm using single-quoted strings. This is a micro-optimization if you don't have variable names that need to be substituted.
Now you need to generate a CSV string from this array, it can be done like this:
echo implode(',', $array);
One method is by using substr
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
$output = "";
foreach($array as $i=>$k)
{
$output .= $i.'-'.$k.',';
}
$output = substr($output, 0, -1);
echo $output;
Another method would be using implode
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
$output = array();
foreach($array as $i=>$k)
{
$output[] = $i.'-'.$k;
}
echo implode(',', $output);
I don't like this idea of using substr at all, since it's the style of bad programming. The idea is to concatenate all elements and to separate them by special "separating" phrases. The idea to call the substring for that is like to use a laser to shoot the birds.
In the project I am currently dealing with, we try to get rid of bad habits in coding. And this sample is considered one of them. We force programmers to write this code like this:
$first = true;
$result = "";
foreach ($array as $i => $k) {
if (!$first) $result .= ",";
$first = false;
$result .= $i.'-'.$k;
}
echo $result;
The purpose of this code is much clearer, than the one that uses substr. Or you can simply use implode function (our project is in Java, so we had to design our own function for concatenating strings that way). You should use substr function only when you have a real need for that. Here this should be avoided, since it's a sign of bad programming style.
I always use this method:
$result = '';
foreach($array as $i=>$k) {
if(strlen($result) > 0) {
$result .= ","
}
$result .= $i.'-'.$k;
}
echo $result;
try this code after foreach condition then echo $result1
$result1=substr($i, 0, -1);
Assuming the array is an index, this is working for me. I loop $i and test $i against the $key. When the key ends, the commas do not print. Notice the IF has two values to make sure the first value does not have a comma at the very beginning.
foreach($array as $key => $value)
{
$w = $key;
//echo "<br>w: ".$w."<br>";// test text
//echo "x: ".$x."<br>";// test text
if($w == $x && $w != 0 )
{
echo ", ";
}
echo $value;
$x++;
}
this would do:
rtrim ($string, ',')
see this example you can easily understand
$name = ["sumon","karim","akash"];
foreach($name as $key =>$value){
echo $value;
if($key<count($name){
echo ",";
}
}
I have removed comma from last value of aray by using last key of array. Hope this will give you idea.
$last_key = end(array_keys($myArray));
foreach ($myArray as $key => $value ) {
$product_cateogry_details="SELECT * FROM `product_cateogry` WHERE `admin_id`='$admin_id' AND `id` = '$value'";
$product_cateogry_details_query=mysqli_query($con,$product_cateogry_details);
$detail=mysqli_fetch_array($product_cateogry_details_query);
if ($last_key == $key) {
echo $detail['product_cateogry'];
}else{
echo $detail['product_cateogry']." , ";
}
}
$foods = [
'vegetables' => 'brinjal',
'fruits' => 'orange',
'drinks' => 'water'
];
$separateKeys = array_keys($foods);
$countedKeys = count($separateKeys);
for ($i = 0; $i < $countedKeys; $i++) {
if ($i == $countedKeys - 1) {
echo $foods[$separateKeys[$i]] . "";
} else {
echo $foods[$separateKeys[$i]] . ", \n";
}
}
Here $foods is my sample associative array.
I separated the keys of the array to count the keys.
Then by a for loop, I have printed the comma if it is not the last element and removed the comma if it is the last element by $countedKeys-1.

Categories