What is the most obvious to declare a multi-dimensional array? - php

I have started to understand the 2D array and multi-dimensional array, some reference books mentioned it has different ways to declare them. Which methods will be declare the array more easier and easy to understand?
method 1:
$pgmCode = array
(
"Item1"=>array("...","..."=>array("..."=>1)),
......
)
Or method2:
$A['ABC']['...'] = '3';
$A['...']['...']['...'] = '2';
Furthermore, if I will build a database and calling the data as array store, which method will be preferred to use?
Thanks.

$pgmCode = array(
"item1" = array(
"subItem1" => true,
"subItem2" => array("subSubItem1", "subSubItem2"),
),
"item2" = array(
"subItem1" => true,
"subItem2" => array("subSubItem1", "subSubItem2"),
),
);
Watchout with mixed use of array and string item in an array, if you will do a in_array() on a mixed variable array it will always return true if you don't use the strict mode of the function.
in your method 1
in_array("something", $pgmCode['Item1']); //return true
in_array("something", $pgmCode['Item1'], true); //return false

$pgmCode = array
(
"Item1"=>array("...","..."=>array("..."=>1)),
"Item1"=>array("...","..."=>array("..."=>1)),
......
);
makes it more understandable.

Related

Sort data array structure in php for Czech language

I am getting JSON in php from remote API and after that with usort i am sorting data arrays from a to z. But i need to sort it in Czech alphabet.
This is my current code:
$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body, true )['data']['items'];
usort($data,function($a,$b) {return strnatcasecmp($a['city'],$b['city']);});
Can you help me?
Thanks
Since you did not provide the array structure I just assumed one.
$data = array(
'items' => array(
0 => array('city' => 'Froni'),
1 => array('city' => 'Frans'),
2 => array('city' => 'Frédéric')
),
);
usort($data['items'],
function($a,$b) {
$coll = collator_create( 'fr_FR' );
$aSortKey = collator_get_sort_key($coll, $a['city']);
$bSortKey = collator_get_sort_key($coll, $b['city']);
return $aSortKey >= $bSortKey;
}
);
var_dump($data['items']);
This takes advantage of the Collator Sort Key rather than comparing the strings itself and is used to sort the strings within your usort anonymous function. You will most likely have to change the parameters going in the usort function and its locale, though.

php make a json object not working as expected

This is my code:
$amenitiesObject = array('parameter-amenities' => array('value' => $amenities));
$buildingObject = array('parameter-building' => array('value' => $building));
$data = array($amenitiesObject, $buildingObject);
$post_data = json_encode($data, JSON_FORCE_OBJECT);
return $post_data;
the result is:
{"0":{"parameter-amenities":{"value":""}},"1":{"parameter-building":{"value":""}}}
while i was hoping for this:
{"parameter-amenities":{"value":""},"parameter-building":{"value":""}}
what is my mistake please?
While #fusion3k's comment is correct and doing $data = array_merge( $amenitiesObject, $buildingObject ); fixes it, I'd like to explain it a little further so you can avoid this type of scenario.
When you do $data = array($amenitiesObject, $buildingObject);, you are not creating a merge of both arrays, you are creating an array with index 0 equals to $amenitiesObject and index 1 equals to $buildingObject, the equivalent of doing :
array(0 => $amenitiesObject, 1 => $buildingObject);
So the json_encode part is working as expected.
When you use array_merge, you maintain only ONE array, that is a combination on both arrays, so you have the expected result.

PHP Prepend two elements to associative array

I have the following array, I'm trying to append the following ("","--") code
Array
(
[0] => Array
(
[Name] => Antarctica
)
)
Current JSON output
[{"Name":"Antarctica"}]
Desired output
{"":"--","Name":"Antarctica"}]
I have tried using the following:
$queue = array("Name", "Antarctica");
array_unshift($queue, "", "==");
But its not returning correct value.
Thank you
You can prepend by adding the original array to an array containing the values you wish to prepend
$queue = array("Name" => "Antarctica");
$prepend = array("" => "--");
$queue = $prepend + $queue;
You should be aware though that for values with the same key, the prepended value will overwrite the original value.
The translation of PHP Array to JSON generates a dictionary unless the array has only numeric keys, contiguous, starting from 0.
So in this case you can try with
$queue = array( 0 => array( "Name" => "Antarctica" ) );
$queue[0][""] = "--";
print json_encode($queue);
If you want to reverse the order of the elements (which is not really needed, since dictionaries are associative and unordered - any code relying on their being ordered in some specific way is potentially broken), you can use a sort function on $queue[0], or you can build a different array:
$newqueue = array(array("" => "--"));
$newqueue[0] += $queue[0];
which is equivalent to
$newqueue = array(array_merge(array("" => "--"), $queue[0]));
This last approach can be useful if you need to merge large arrays. The first approach is probably best if you need to only fine tune an array. But I haven't ran any performance tests.
Try this:
$queue = array(array("Name" => "Antarctica")); // Makes it multidimensional
array_unshift($queue, array("" => "--"));
Edit
Oops, just noticed OP wanted a Prepend, not an Append. His syntax was right, but we was missing the array("" => "--") in his unshift.
You can try this :
$queue = array("Name" => "Antarctica");
$result = array_merge(array("" => "=="), $queue);
var_dump(array_merge(array(""=>"--"), $arr));

Applying a variable level array to an existing array

I have two arrays, one of which is a "section" of the other. For example:
$array = array('file_name1'=>'date1',
'file_name2'=>'date2',
'file_name3'=> array('file_name3.1'=>'date3.1',
'file_name3.2'=>'date3.2'),
'file_name4'=>'date4');
$array_part = array('file_name3'=>array('file_name3.2'=>'date3.2.2'));
In my script, the first array holds a directory structure with the final values being the last-modified date. When I find a change, I want to apply the date value from the second array into the original array. Both arrays are dynamically created, so I don't know the depth of either array. How can I apply this value to the original array?
You are most likely looking for array_replace_recursive:
print_r(
array_replace_recursive($array, $array_part)
);
Which gives in your case:
Array
(
[file_name1] => date1
[file_name2] => date2
[file_name3] => Array
(
[file_name3.1] => date3.1
[file_name3.2] => date3.2.2
)
[file_name4] => date4
)
Example Code (Demo):
<?php
/**
* Applying a variable level array to an existing array
*
* #link http://stackoverflow.com/q/18519457/367456
*/
$array = array('file_name1' => 'date1',
'file_name2' => 'date2',
'file_name3' => array('file_name3.1' => 'date3.1',
'file_name3.2' => 'date3.2'),
'file_name4' => 'date4');
$array_part = array('file_name3' => array('file_name3.2' => 'date3.2.2'));
print_r(
array_replace_recursive($array, $array_part)
);
you can use php referneces
a data can be found here:
http://php.net/manual/en/language.references.pass.php
<?php
function foo(&$var)
{
$var++;
}
function &bar()
{
$a = 5;
return $a;
}
foo(bar());
?>

PHP Convert variable names to lowercase?

I have an api listener script which takes in get parameters. But I seem to be having issues when users tend to pass mixed case variable names on the parameters.
For example:
http://mylistenerurl.com?paramName1=Hello&paramname2=World
I need my listener to be flixible in such a way that the variable names will be interpreted case-insensitively or rather still all in lower case like after I process the query string on some function, they are all returned as lower-cased variables:
extract(someFunction($_GET));
process($paramname1, $paramname2);
Can anybody shed some light on this?
*much appreciated. thanks!
This should do the trick:
$array_of_lower_case_strings = array_map( "strtolower", array( "This Will Be ALL lowercase.", ... ) );
So in your case:
$get_with_lowercase_keys = array_combine(
array_map( "strtolower", array_keys( $_GET ) ),
array_values( $_GET )
);
One thing I'll mention is you should be VERY careful with extract as it could be exploited to allow unexpected variables to be injected into your PHP.
Apply to your global variables ($_GET, $_POST) when necessary:
e.g. setLowerCaseVars($_GET); in your case
function setLowerCaseVars(&$global_var) {
foreach ($global_var as $key => &$value) {
if (!isset($global_var[strtolower($key)])) {
$global_var[strtolower($key)] = $value;
}
}
}
Edit: Note that I prefer this to using array_combine because it will not overwrite cases where the lower-case variable is already set.
PHP has had a native function (array_change_key_case()) for this task since version 4.2 to change the case of first level keys. To be perfectly explicit -- this function can be used to convert first level key to uppercase or lower case BUT this is not a recursive function so deeper keys will not be effected.
Code: (Demo)
parse_str('paramName1=Hello&paramname2=World&fOo[bAR][BanG]=boom', $_GET);
var_export($_GET);
echo "\n---\n";
$lower = array_change_key_case($_GET);
var_export($lower);
Output:
array (
'paramName1' => 'Hello',
'paramname2' => 'World',
'fOo' =>
array (
'bAR' =>
array (
'BanG' => 'boom',
),
),
)
---
array (
'paramname1' => 'Hello', # N changed to n
'paramname2' => 'World',
'foo' => # O changed to o
array (
'bAR' => # AR not changed because not a first level key
array (
'BanG' => 'boom', # B and G not changed because not a first level key
),
),
)

Categories