I am trying to create an associative array using php. My desired output is
Array
(
[key] => fl_0_sq
),
Array
(
[key] => fl_1_sq
)
The code is
$max_val = 2;
for($i=0; $i<$max_val; $i++)
{
$flr_arr .= "array('key' => 'fl_".$i."_sq'),";
}
print_r($flr_arr);
Output is
array('key' => 'fl_0_sq'),array('key' => 'fl_1_sq'),
Now the issue is that it has become a string instead of an array. Is it at all possible to create a array structure like the desired output. Any help is highly appreciated.
You could do this:
<?php
$flr_arr = [];
$max_val = 2;
for ($i = 0; $i < $max_val; $i++) {
$flr_arr[][key] = 'fl_' . $i . '_sq';
}
$output = "<pre>";
foreach ($flr_arr as $i => $flr_arr_item) {
$output .= print_r($flr_arr_item, true);
if($i < count($flr_arr)-1){
$output = substr($output, 0, -1) . ",\n";
}
}
$output .= "</pre>";
echo $output;
The output:
Array
(
[key] => fl_0_sq
),
Array
(
[key] => fl_1_sq
)
I'm not exactly sure what you want to do, but your output could be done by this:
$max_val = 2;
for($i=0; $i<$max_val; $i++)
{
$flr_arr = [];
$flr_arr['key'] = 'fl_".$i."_sq';
print_r($flr_arr);
}
You're declaring a string and concatenating it. You want to add elements to an array. You also can't create multiple arrays with the same name. What you can do, though is a 2D array:
$flr_arr[] = array("key"=>"fl_$i_sq");
Note the lack of quotes around array(). The "[]" syntax adds a new element to the end of the array. The output would be -
array(array('key' => 'fl_0_sq'),array('key' => 'fl_1_sq'))
Related
I want to achieve this
foreach($spacecount as $x => $x_value) {
if($spacecount[$x+1] < $spacecount[$x+2] ) {
echo $spacecount[$x];
}
}
like we can do it in for loop, but i also want to use its key when needed. how can I perform it ?
The array looks like
Array ( [ Tables] => 5
[Home] => 0
[ Wallet] => 5
[Designer] => 0
)
it contains whitespaces in the key text
If there's no guarantee that your array is numerically indexed, you can do this:
$keys = array_keys($spacecount);
$values = array_values($spacecount);
for ($i = 0;$i < count($spacecount)-2;$i++) {
//If you need the key you can use $keys[$i]
if ($values[$i+1] < $values[$i+2]) {
echo $values[$i+1];
}
}
I want to make a sitemap generator and the generated sitemap must be be like a tree.Can someone point me to an algorithm that does this? Or does anyone know the algorithm?
The structure of the sitemap should look like something like this :
I was thinking to use arrays to do this but i can't think of an algorithm to get all links from the website and build the arrays.
I came up with
<?php
$links = array('bla.com/bla1/bla2', 'bla.com/bla1', 'bla.com/bla1/bla3', 'bla.com', 'bla.com/blabla/bla1/bla4', 'bla.com/blabla/otherbla/onemorebla');
$links = array_fill_keys($links, 0);
foreach($links as $key => $value){
$levelsNumber = count(explode('/', $key));
$links[$key] = $levelsNumber;
}
$output = array();
$maxLevel = 1;
foreach ($links as $link => $levels){
if ($levels > $maxLevel) $maxLevel = $levels;
}
for($level = 1; $level <= $maxLevel; $level++){
foreach ($links as $link => $levels){
$parts = explode('/', $link);
if (count($parts) >= $level){
$levelExists = false;
if (!$levelExists){
$keysString = '';
for ($j = 0; $j < $level; $j++){
$keysString .= "['".$parts[$j]."']";
}
eval('$output'.$keysString.'= NULL;');
$levelExists = true;
}
}
}
}
print_r($output);
?>
running it gives
Array
(
[bla.com] => Array
(
[bla1] => Array
(
[bla2] =>
[bla3] =>
)
[blabla] => Array
(
[bla1] => Array
(
[bla4] =>
)
[otherbla] => Array
(
[onemorebla] =>
)
)
)
)
I think if you play with it you might get what you've expected.
CURRENT ARRAY:
stdClass Object (
[name1] => Someting very useful
[text1] => Description of something useful
[url1] => link.to/useful
[name2] => Someting very useful2
[text2] => Description of something useful2
[url2] => link.to/useful2
[name3] => Someting very useful3
[text3] => Description of something useful3
[url3] => link.to/useful3
)
I NEED:
To create multidimensional array where keys like name1, text1, url1 (and so on) will be putted into own array. How to accomplish that?
I think you want:
$array = array_chunk((array)$object, $chunkSize = 3, $preserveKeys = true);
($object is your object above)
This will cast your object to an array, and split it into smaller arrays of 3 elements each
Well;
$array = (array) $object;
$array = array();
$c = count($object) / 3;
(Array) $object;
for($i = 1; $i <= $c; $i++){
$array[$i]['name' + $i] = $object['name' + $i];
$array[$i]['text' + $i] = $object['text' + $i];
$array[$i]['url' + $i] = $object['url' + $i];
}
This would be very versatile even if you don't have consistent input, like exactly three properties per child. Also the properties in the object don't have to be in any particular order.
//$obj is the object you have in the question
$objects = array();
foreach($obj as $key => $val) {
$result = preg_match('%([a-zA-Z]+)([0-9]+)%', $key,$matches);
$new_key = $matches[2];
$property = $matches[1];
if(!isset($objects[$new_key])) {
$objects[$new_key] = array();
}
$objects[$new_key][$property] = $val;
}
I have the following Arrays:
$front = array("front_first","front_second");
$inside = array("inside_first", "inside_second", "inside_third");
$back = array("back_first", "back_second", "back_third","back_fourth");
what I need to do is combine it so that an output would look like this for the above situation. The output order is always to put them in order back, front, inside:
$final = array(
"back_first",
"front_first",
"inside_first",
"back_second",
"front_second",
"inside_second",
"back_third",
"front_second",
"inside_third",
"back_fourth",
"front_second",
"inside_third"
);
So basically it looks at the three arrays, and whichever array has less values it will reuse the last value multiple times until it loops through the remaining keys in the longer arrays.
Is there a way to do this?
$front = array("front_first","front_second");
$inside = array("inside_first", "inside_second", "inside_third");
$back = array("back_first", "back_second", "back_third","back_fourth");
function foo() {
$args = func_get_args();
$max = max(array_map('sizeof', $args)); // credits to hakre ;)
$result = array();
for ($i = 0; $i < $max; $i += 1) {
foreach ($args as $arg) {
$result[] = isset($arg[$i]) ? $arg[$i] : end($arg);
}
}
return $result;
}
$final = foo($back, $front, $inside);
print_r($final);
demo: http://codepad.viper-7.com/RFmGYW
Demo
http://codepad.viper-7.com/xpwGha
PHP
$front = array("front_first", "front_second");
$inside = array("inside_first", "inside_second", "inside_third");
$back = array("back_first", "back_second", "back_third", "back_fourth");
$combined = array_map("callback", $back, $front, $inside);
$lastf = "";
$lasti = "";
$lastb = "";
function callback($arrb, $arrf, $arri) {
global $lastf, $lasti, $lastb;
$lastf = isset($arrf) ? $arrf : $lastf;
$lasti = isset($arri) ? $arri : $lasti;
$lastb = isset($arrb) ? $arrb : $lastb;
return array($lastb, $lastf, $lasti);
}
$final = array();
foreach ($combined as $k => $v) {
$final = array_merge($final, $v);
}
print_r($final);
Output
Array
(
[0] => back_first
[1] => front_first
[2] => inside_first
[3] => back_second
[4] => front_second
[5] => inside_second
[6] => back_third
[7] => front_second
[8] => inside_third
[9] => back_fourth
[10] => front_second
[11] => inside_third
)
Spreading the column data from multiple arrays with array_map() is an easy/convenient way to tranpose data. It will pass a full array of elements from the input arrays and maintain value position by assigning null values where elements were missing.
Within the custom callback, declare a static cache of the previously transposed row. Iterate the new transposed row of data and replace any null values with the previous rows respective element.
After transposing the data, call array_merge(...$the_transposed_data) to flatten the results.
Code: (Demo)
$front = ["front_first", "front_second"];
$inside = ["inside_first", "inside_second", "inside_third"];
$back = ["back_first", "back_second", "back_third", "back_fourth"];
var_export(
array_merge(
...array_map(
function(...$cols) {
static $lastSet;
foreach ($cols as $i => &$v) {
$v ??= $lastSet[$i];
}
$lastSet = $cols;
return $cols;
},
$back,
$front,
$inside
)
)
);
Output:
array (
0 => 'back_first',
1 => 'front_first',
2 => 'inside_first',
3 => 'back_second',
4 => 'front_second',
5 => 'inside_second',
6 => 'back_third',
7 => 'front_second',
8 => 'inside_third',
9 => 'back_fourth',
10 => 'front_second',
11 => 'inside_third',
)
If you have an associative array:
Array
(
[uid] => Marvelous
[status] => 1
[set_later] => Array
(
[0] => 1
[1] => 0
)
[op] => Submit
[submit] => Submit
)
And you want to access the 2nd item, how would you do it? $arr[1] doesn't seem to be working:
foreach ($form_state['values']['set_later'] as $fieldKey => $setLater) {
if (! $setLater) {
$valueForAll = $form_state['values'][$fieldKey];
$_SESSION[SET_NOW_KEY][array_search($valueForAll, $form_state['values'])] = $valueForAll; // this isn't getting the value properly
}
}
This code is supposed to produce:
$_SESSION[SET_NOW_KEY]['status'] = 1
But it just produces a blank entry.
Use array_slice
$second = array_slice($array, 1, 1, true); // array("status" => 1)
// or
list($value) = array_slice($array, 1, 1); // 1
// or
$blah = array_slice($array, 1, 1); // array(0 => 1)
$value = $blah[0];
I am a bit confused. Your code does not appear to have the correct keys for the array. However, if you wish to grab just the second element in an array, you could use:
$keys = array_keys($inArray);
$key = $keys[1];
$value = $inArray[$key];
However, after considering what it appears you're trying to do, something like this might work better:
$ii = 0;
$setLaterArr = $form_state['values']['set_later'];
foreach($form_state['values'] as $key => $value) {
if($key == 'set_later')
continue;
$setLater = $setLaterArr[$ii];
if(! $setLater) {
$_SESSION[SET_NOW_KEY][$key] = $value;
}
$ii ++;
}
Does that help? It seems you are trying to set the session value if the set_later value is not set. The above code does this. Instead of iterating through the inner array, however, it iterates through the outer array and uses an index to track where it is in the inner array. This should be reasonably performant.
You can use array_slice to get the second item:
$a= array(
'hello'=> 'world',
'how'=> 'are you',
'an'=> 'array',
);
$second= array_slice($a, 1, 1, true);
var_dump($second);
Here's a one line way to do it with array_slice and current
$value = current(array_slice($array, 1, 1)); // returns value only
If the array you provide in the first example corresponds to $form_state then
$form_state['values']['set_later'][1]
will work.
Otherwise
$i = 0;
foreach ($form_state['values']['set_later'] as $fieldKey => $setLater) {
if ($i == 1) {
$valueForAll = $form_state['values'][$fieldKey];
$_SESSION[SET_NOW_KEY][$fieldKey] = $setLater;
continue;
}
$i++;
}
Every one of the responses here are focused on getting the second element, independently on how the array is formed.
If this is your case.
Array
(
[uid] => Marvelous
[status] => 1
[set_later] => Array
(
[0] => 1
[1] => 0
)
[op] => Submit
[submit] => Submit
)
Then you can get the value of the second element via $array['status'].
Also this code
foreach ($form_state['values']['set_later'] as $fieldKey => $setLater) {
if (! $setLater) {
$valueForAll = $form_state['values'][$fieldKey];
$_SESSION[SET_NOW_KEY][array_search($valueForAll, $form_state['values'])] = $valueForAll; // this isn't getting the value properly
}
}
I don't understand what are you trying to do, care to explain?
/**
* Get nth item from an associative array
*
*
* #param $arr
* #param int $nth
*
* #return array
*/
function getNthItemFromArr($arr, $nth = 0){
$nth = intval($nth);
if(is_array($arr) && sizeof($arr) > 0 && $nth > 0){
$arr = array_slice($arr,$nth-1, 1, true);
}
return $arr;
}//end function getNthItemFromArr