php put arrays in arrays - php

I want to push some items in one array, here is the structure:
$str = 'String';
$a = array('some', 'sub', 'page');
and I want to push the items to some other array that should become:
Array (
[some] => Array (
[sub] => Array (
[page] => String
)
)
)
I don't know how exactly to explain it, so hope the example shows you something.
I want any new element in the first array (a) to be pushed as sub-array of the prevous one and the last to have the value from $str;
$string = 'My Value';
$my_first_array = array('my', 'sub', 'arrays');
Then some function to parse $my_first_array and transfer it as:
Example:
ob_start('nl2br');
$my_parsed_sub_array = parse_sub_arrays($my_first_array, $string);
print_r($my_parsed_sub_array);
===>>>
Array (
[my] => Array (
[sub] => Array (
[arrays] => String
)
)
)

[Edit] I hope that, this time, I've understood the question...
If you have your string and array like this :
$str = 'test';
$a = array('some', 'sub', 'page');
You could first initialize the resulting array this way, dealing with that special case of the last item :
$arr = array($a[count($a)-1] => $str);
Then, you can loop over each item of your $a array, starting from the end (and not working on the last item, which we've dealt with already) :
for ($i=count($a) - 2 ; $i>=0 ; $i--) {
$arr = array($a[$i] => $arr);
}
With this, dumping the resulting array :
var_dump($arr);
Should get you the expected result :
array
'some' =>
array
'sub' =>
array
'page' => string 'test' (length=4)
Old answer below, before understanding the question :
You could declare your array this way :
$arr = array(
'some' => array(
'sub' => array(
'page' => $str,
),
),
);
Or, using several distinct steps (might be easier, depending on the way you construct your sub-arrays, especially in a more complex case than the current example) :
$sub2 = array('page' => $str);
$sub1 = array('sub' => $sub2);
$arr = array('some' => $sub1);

Related

Multidimesional array pointers

I'm building an array piece by piece following a specific pattern.
For example, I have this string <val0=0, val1=<val2=2, val3=<val4=4>>, val5=5> and I need to translate it to an associative array. So every time I find < I have to create a new array and store the following elements until the next >.
The string above should result in something like this:
Array
(
[val0] => 0
[val1] => Array
(
[val2] => 2
[val3] => Array
(
[val4] => 4
)
)
[val5] => 5
)
Everything is working fine for non-multidimensional arrays using str_split to break the string in pieces and iterating over them in a for loop but I'm having difficulties to find a workaround every time there is a nesting array in the string.
What I need is a way to have a pointer to the last created array inside the main array.
Is there a way to store an array pointer reference in a variable so I could do this:
print_r($MULTIARRAY['val1']['val3']);
// prints: array()
$pointer = pointer($MULTIARRAY['val1']['val3']);
$pointer[] = 'AAA';
$pointer[] = 'BBB';
print_r($MULTIARRAY['val1']['val3']);
// prints: array(
// [0] => AAA
// [1] => BBB
//)
Here you go, it's called reference
$a[1][22] = array();
$pointer = &$a[1][22];
$pointer[] = 3;
$pointer[] = 4;
print_r($a);

PHP Array - brackets

does someone know the meaning of the [ ] in the creation of a PHP array, and if it's really needed. Becasuse from my point of view. Both ways are sufficinent
Way 1, with brackets:
$cars[] = array ('expensive' => $BMW,
'medium' => $Volvo,
'cheap' => $Lada);
Way2, without brackets:
$cars = array ('expensive' => $BMW,
'medium' => $Volvo,
'cheap' => $Lada);
Read http://php.net/manual/en/function.array-push.php for a clear answer as to the differences.
main differences:
citing array() can only be done when creating the variable.
$var[] can add values to arrays that already exist.
$var[] will create an array and is in effect the same function call as $var = array(...);
also
You can not assign multiple values in a single declaration using the $var[] approach (see example 4, below).
some work throughs:
1) Using array()
$cars = "cats";
$cars = array("cars","horses","trees");
print_r($cars) ;
Will output
$cars --> [0] = cars
[1] = horses
[2] = trees
2) Appending Values
Then writing $cars = array("goats"); will NOT append the value but will instead initialise a NEW ARRAY, giving:
$cars --> [0] = goats
But if you use the square brackets to append then writing $cars[] = "goats" will give you :
$cars --> [0] = cars
[1] = horses
[2] = trees
[3] = goats
Your original question means that whatever is on the right hand side of the = sign will be appended to current array, if the left hand side has the syntax $var[] but this will be appended Numerically. As shown above.
You can append things by key name by filling in the key value: $cars['cheap'] = $Lada; .
Your example 1 is setting that an array is held within an array, so to access the value $Lada you would reference $cars[0]['cheap'] . Example 2 sets up the array but will overwrite any existing array or value in the variable.
3) String And Numerical Indexing
The method of using the array(...) syntax is good for defining multiple values at array creation when these values have non-numeric or numerically non-linear keys, such as your example:
$cars = array ('expensive' => "BMW",
'medium' => "Volvo",
'cheap' => "Lada");
Will output at array of:
$cars --> ['expensive'] = BMW
['medium'] = Volvo
['cheap'] = Lada
But if you used the alternative syntax of:
$cars[] = "BMW";
$cars[] = "Volvo";
$cars[] = "Lada";
This would output:
$cars --> [0] = BMW
[1] = Volvo
[2] = Lada
4) I'm still writing....
As another example: You can combine the effects of using array() and $var[] with key declarations within the square brackets thus:
$cars['expensive'] = "BMW";
$cars['medium'] = "Volvo";
$cars['budget'] = "Lada";
giving:
$cars --> ['expensive'] = BMW
['medium'] = Volvo
['cheap'] = Lada
(my original answer was verbose and not very great).
5) Finally.....
So what happens when you combine the two styles, mixing the array() declaration with the $var[] additions:
$ray = array("goats" => "horny", "knickers" => "on the floor", "condition" => "sour cream");
$ray[] = "crumpet";
$ray[] = "bread";
This will maintain both numeric and string key indexes in the array, outputting with print_r():
$ray --> [goats] => horny
[knickers] => on the floor
[condition] => sour cream
[0] => crumpet
[1] => bread
They are different. The first one is an array inside of another one
$cars[] = array ('expensive' => "BMW",
'medium' => "Volvo",
'cheap' => "Lada");
var_dump($cars);
array (size=1)
0 =>
array (size=3)
'expensive' => string 'BMW' (length=3)
'medium' => string 'Volvo' (length=5)
'cheap' => string 'Lada' (length=4)
The second one is just an array
$cars = array ('expensive' => "BMW",
'medium' => "Volvo",
'cheap' => "Lada");
var_dump($cars);
array (size=3)
'expensive' => string 'BMW' (length=3)
'medium' => string 'Volvo' (length=5)
'cheap' => string 'Lada' (length=4)
way 1 results an array with array values (array of array)
whereas way2 is array which contains mentioned values
Way 1 adds your new array() at the end of the existing array. So if you have 2 elements inside that array already, a third one with the array you specified will be created.
Way 2 is the typical array creation - just that some other variables are used to fill the fields.
Simply to complete your exercise, here is way 3:
$arr = array();
$arr[1] = array("foo"=>"bar");
This puts the foo:bar array at entry #1 into the $arr variable.
The second example is clear. In the first example you are adding an array element without specifying its key, hence the empty brackets []. As the array is not yet initialized, its created at the same time. The result is, as others already pointed out, a multidimensional array.
Beware though that the first way is not encouraged:
If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize variable by a direct assignment.
If $cars was already set, e.g. to a string, you would get an error.
$cars = 'test';
$cars[] = array ('expensive' => $BMW,
'medium' => $Volvo,
'cheap' => $Lada);
Method 1, with brackets: Multidimensional array
Array ( [0] => Array ( [expensive] => 12 [medium] => 13 [cheap] => 14 ) )
Method 2, with brackets: Associative array
Array ( [expensive] => 12 [medium] => 13 [cheap] => 14 )

What will array_column return if a key name doesn't exist?

According to https://wiki.php.net/rfc/array_column array_column is slated to be added to PHP soon. But I having trouble understanding the RFC. What will be returned if a named key doesn't exist?
Example:
$arr = array(
array(
'firstname' => 'Bob',
'lastname' => 'Tomato'
),
array(
'firstname' => 'Larry',
'lastname' => 'Cucumber'
)
);
$middlenames = array_column($arr, 'middlename');
Introduction
For you to understand the RFC you need to understand the problem first and the reason it was introduced.
Your Array
$arr = array(
array(
'firstname' => 'Bob', <--
'lastname' => 'Tomato' | <--
), | |
array( | |
'firstname' => 'Larry', <-- |
'lastname' => 'Cucumber' <-|
)
);
Getting Column
To get Bob & Larry or Tomato and Cucumber you have use more than one line of code examples are :
$colums = array();
foreach ( array_map(null, $arr[0], $arr[1]) as $value ) {
$colums[] = $value;
}
print_r($colums);
Output
Array
(
[0] => Array
(
[0] => Bob
[1] => Larry
)
[1] => Array
(
[0] => Tomato
[1] => Cucumber
)
)
Dynamic Version
The code above would only work if you know number of elements another creative way would be
$colums = array();
array_unshift($arr, null);
foreach (call_user_func_array("array_map", $arr) as $value ) {
$colums[] = $value;
}
Live Test
Or Better Sill use MultipleIterator
$mi = new MultipleIterator(MultipleIterator::MIT_NEED_ALL);
foreach ( $arr as $v ) {
$mi->attachIterator(new ArrayIterator($v));
}
$colums = array();
foreach ( $mi as $v ) {
$colums[] = $v;
}
print_r($colums);
Live Test
Key Name
If you need to get the key name here is another method
$colums = array_reduce($arr, function ($a, $b) {
foreach ( $b as $k => $v ) {
$a[$k][] = $v;
}
return $a;
});
Live Test
Back to array_column
array_column intends simply the process and getting all columns with first name would be as simple as the following:
print_r(array_column($arr,"lastname"));
^
|
+--- This get value with key "lastname"
Live Test
More Complex Senerio
Imagine you want your array to have this output
Array
(
[Bob] => Tomato
[Larry] => Cucumber
)
Use Old methods you can have
$colums = array();
array_unshift($arr, null);
foreach (call_user_func_array("array_map", $arr) as $value ) {
$key = array_shift($value);
$colums[$key] = current($value);
}
print_r($colums);
Live Test
Now you can see i had to use array_shift and current to get first 2 element .. as your array grows this can become complex but array_column would simplify this
print_r(array_column($arr,"lastname","firstname"));
^ ^
| |
Value Key (I wonder why position is backwards)
Output
Array
(
[Bob] => Tomato
[Larry] => Cucumber
)
Finally Back to your Question
What will be returned if a named key doesn't exist?
Empty array ... From your example
print_r(array_column($arr,"middlename"));
^
|
it would try to check if any of your array has key middle man
It returns
Array <------- Otherwise returns empty array
(
)
Conclusion
I used so may different examples using loop , array_map , array_reduce and MultipleIterator to explain what array_column is trying to achieve.
As you can see array_column is much more simplified but i would advice you play with the examples in the RFC a little and this would allow you understand it better if you still don't understand it, PHP is a flexible language you can always implement your own version
As per: https://wiki.php.net/rfc/array_column
When a corresponding indexKey cannot be found, the value will be keyed with an integer, starting from zero.
Example used in RFC:
$mismatchedColumns = array(
array(
'a' => 'foo',
'b' => 'bar',
'e' => 'baz'
),
array(
'a' => 'qux',
'c' => 'quux',
'd' => 'corge'
),
array(
'a' => 'grault',
'b' => 'garply',
'e' => 'waldo'
),
);
$foo = array_column($mismatchedColumns, 'a', 'b');
Results in $foo equal to:
Array
(
[bar] => foo
[0] => qux
[garply] => grault
)
Essentially, the value at a becomes the new array value, and b becomes the key. When the original array does not contain the key b, it creates a 0 index and uses that instead. If there were multiple keys that did not exist, they would be incremental from 0.
Looking into their examples a little further, it hints that when you are unable to match a value in the the original array, you won't get an array element at all. This means if you were looking for a single value in an array and it didn't exist, it would return an empty array.
P.S. I've obviously never used this function, so most of this is interpretation of the RFC.
On a side note, this function was accepted for inclusion in PHP and was originally proposed by Ben Ramsey with a final result from voting of 38 in favor and 6 against. The mailing list discussion can be viewed here: http://grokbase.com/t/php/php-internals/126nxxa80p/draft-rfc-array-column-function. See also https://github.com/php/php-src/pull/257

Fetching a multidimensional array

I am trying to edit a plugin that is fetching a multidimensional array, then breaking it out into a foreach statement and doing stuff with the resulting data.
What I am trying to do is edit the array before it gets to the foreach statement. I want to look and see if there is a key/value combination that exists, and if it does remove that entire subarray, then reform the array and pass it to a new variable.
The current variable
$arrayslides
returns several subarrays that look like something like this (I remove unimportant variables for the sake of briefness):
Array (
[0] => Array (
[slide_active] => 1
)
[1] => Array (
[slide_active] => 0
)
)
What I want to do is look and see if one of these subarrays contains the key slide_active with a value of 0. If it contains a value of zero, I want to dump the whole subarray altogether, then reform the multidimensional array back into the variable
$arrayslides
I have tried a few array functions but have not had any luck. Any suggestions?
$arrayslides = array(0 => array ( 'slide_active' => 1, 'other_data' => "Mark" ),
1 => array ( 'slide_active' => 0, 'other_data' => "ABCDE" ),
2 => array ( 'slide_active' => 1, 'other_data' => "Baker" ),
3 => array ( 'slide_active' => 0, 'other_data' => "FGHIJ" ),
);
$matches = array_filter($arrayslides, function($item) { return $item['slide_active'] == 1; } );
var_dump($matches);
PHP >= 5.3.0
I know its not so efficient but still
foreach ($arraySlides as $key => $value)
{
if(in_array('0', array_values($value))
unset($arraySlides[$key]);
}

insert value at the beginning of an array in php

my array is
$hello= array( Code => 'TIR', Description => 'Tires', Price => 100 )
now i want to add a value in array beginning of an array not the end of an array.... and results i want is
$hello= array( ref=>'World', Code => 'TIR', Description => 'Tires', Price => 100 )
UPDATE
actually i need any value that is coming will be added in the beginning of an array....this is not single value.. ref=world.... this is coming from output...like if i add quantity=50, then it should be added beginning of an array before 'ref' an array should be
$hello= array(quantity=>'50', ref=>'World', Code => 'TIR', Description => 'Tires', Price => 100 )
I would use array_merge()
Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
$hello = array ("Code" => "Tir" .....); // you should really put quotes
// around the keys!
$world = array ("ref" => "World");
$merged = array_merge($world, $hello);
You can use the + operator:
$hello = array( 'Code' => 'TIR', 'Description' => 'Tires', 'Price' => 100 );
$hello = array('ref' => 'World') + $hello;
print_r($hello);
would give
Array
(
[ref] => World
[Code] => TIR
[Description] => Tires
[Price] => 100
)
Like Pekka said, you should put quotes around the keys. The PHP manual explicitly states omitting quotes is wrong usage. You might also want to check out my answer about the difference between using the + operator vs using array_merge to decide which you want to use.
$a= array( 'a' => 'a' );
$b = array( 'b' => 'b' );
$res = $b + $a;
//result: ( 'b' => 'b', 'a' => 'a' )
$hello = array_merge(array('ref'=>'World'), $hello);

Categories