PHP: get value from subarray - php

How do I get the value from a subarray? In this case I'm interested in the locale
$objects=
Array
(
[1397300927159026] => Array
(
[category] => 2
[locale] => de_DE
)
[10152395537445743] => Array
(
[category] => 100
[locale] => en_US
)
)
Desired Output:
Array
(
[1397300927159026] => "de_DE"
[10152395537445743] => "en_US"
)
I've tried using a foreach loop to iterate through but the results are a mess -- thanks for any help.

Just a simple foreach would suffice. You just need to create it in another array. Consider this example:
$objects = array(
'1397300927159026' => array('category' => 2, 'locale' => 'de_DE'),
'10152395537445743' => array('category' => 100, 'locale' => 'en_US'),
);
$new_objects = array();
foreach($objects as $key => $value) {
// $key will contain = 1397300927159026, and 1397300927159026
// set that key into the new array as key also
$new_objects[$key] = $value['locale'];
}
echo '<pre>';
print_r($new_objects);
echo '</pre>';
Sample Output:
Array
(
[1397300927159026] => de_DE
[10152395537445743] => en_US
)

This is what array_map() is for. It loops through the array and applies a callback function to each value and returns the modified array.
$objects = array_map( function( $val ) {
return $val['locale'];
}, $objects );

Check this CodeViper Demo
PHP
<?php
$objects=
Array
(
'1397300927159026' => Array
(
'category' => 2,
'locale' => 'de_DE'
),
'10152395537445743' => Array
(
'category' => 100,
'locale' => 'en_US'
)
);
$arr = array();
foreach($objects as $key => $value) {
$arr[$key] = $value['locale'];
}
print_r($arr);
?>
Result
Array ( [1397300927159026] => de_DE [10152395537445743] => en_US )

You can easily do it with a foreach loop and a new array.
Declare a new array say $abc
<?php
$abc = array();
//Going to loop through original array ($objects) as key and values.
foreach($objects as $key => $val ) {
// $key will contain values 1397300927159026, 10152395537445743
// $val['category'] contain values 2,100
// $val['locale'] contain values de_DE, en_US
$abc[$key] = $val['locale'];
}
print_r($abc);
?>

Replace each subarray with its last element's value? array_map() with end() is pretty succinct ...though it requires your application to keep the element at the end of the subarrays -- so arguably less trustworthy.
Also $objects is a poor variable name choice for a multidimensional array.
Code: (Demo)
var_export(array_map('end', $objects));
Output:
array (
1397300927159026 => 'de_DE',
10152395537445743 => 'en_US',
)

Related

PHP generate one array index with many values and remove empty array values

I have this array:
[docs] => Array
(
[indexone] => Array ( [0] => P008062518 )
[indextwo] => Array ( [0] => )
[indexthree] => Array ( [0] => 0000141334 )
[indexfour] => Array ( [0] => P006871638 )
[indexfive] => Array ( [0] => 0000910067 )
[indexsix] => Array ( [0] => )
)
I need to end with this one, extracting all values from the given key:
[docValues] => Array
(
[indexone] => Array ( P008062518, 0000141334, P006871638, 0000910067 )
)
I try this loop but i end with the same array structure :
foreach($values as $key => $data)
{
if(array_key_exists('docs', $data) )
{
$filtered = array_filter($data['docs'], function($var) { return !empty($var);});
$numDocs = array_values($filtered);
$values[$key]['docValues'] = $numDocs;
}
}
How can it be done ?
To get that exact array output:
$result['docValues'][key($values['docs'])] =
array_filter(array_column($values['docs'], 0));
Get the first key to use it as your new key with key()
Get an array of all values in the 0 indexes with array_column()
Remove empty elements using array_filter()
If your first array is called $docArray, then you can do the following:
$docValuesArray = array();//declaring the result array
$indexoneArray = array();//declaring the array you will add values
//to in the foreach loop
foreach ($docArray as $value)
{
$indexoneArray[] = $value[0];//giving each of the values
//found in $docArray to the $indexoneArray
}
$docValueArray[] = $indexoneArray;//adding the $indexoneArray
//to the $docsValueArray
Let me know if that worked for you.
This should do the trick for you:
$docs = [
'indexone' => ['P008062518'],
'indextwo' => [ ],
'indexthree' => ['0000141334'],
'indexfour' => ['P006871638'],
'indexfive' => ['0000910067'],
'indexsix' => [ ],
];
$allDocs = array();
foreach($docs as $key => $doc) {
$docString = implode("<br>",$doc);
if (empty($docString)) {
continue;
}
$allDocs[] = $docString;
}
$allDocsString = implode("<br>",$allDocs);
echo($allDocsString);
P0080625180000141334P0068716380000910067
Simply do this:
Your array
$arr = array("docs" =>
array(
'indexone' => array('P008062518'),
'indextwo' => array(''),
'indexthree' => array('0000141334'),
'indexfour' => array('P006871638'),
'indexfive' => array('0000910067'),
'indexsix' => array('')
)
);
Process:
echo '<pre>';
$index = key($arr["docs"]);
$output['docValues'][$index] = implode('<br/>', array_filter(array_column($arr['docs'], 0)));
print_r($output);
Explanation:
key = key function Returns the first index.
implode = collapse all the array items with the delimiter of <br/>
array_filter = filters the values of an array using a callback
function.
array_column = returns the values from a single column in the input
array.
Result:
Array
(
[docValues] => Array
(
[indexone] => P008062518<br/>0000141334<br/>P006871638<br/>0000910067
)
)
use array_filter() function . if you pass array in array_filter then remove all empty and NULL data record

PHP Puttin values of array into multidimensional array

Hello I want to put values of single array into a multidimensional array with each value on a n+1
This is my array $structures
Array
(
[0] => S
[1] => S.1
[2] => S-VLA-S
[3] => SB
[4] => SB50
)
What I want for output is this
Array
(
[S] => Array(
[S.1] => Array (
[S-VLA-S] => Array (
[SB] => Array (
[SB50] => Array(
'more_attributes' => true
)
)
)
)
)
)
This is what I have tried so far
$structures = explode("\\", $row['structuurCode']);
foreach($structures as $index => $structure) {
$result[$structure][$structure[$index+1]] = $row['structuurCode'];
}
The values of the array is a tree structure that's why it would be handy to have them in an multidimensional array
Thanks in advance.
It becomes pretty trivial once you start turning it inside out and "wrap" the inner array into successive outer arrays:
$result = array_reduce(array_reverse($structures), function ($result, $key) {
return [$key => $result];
}, ['more_attributes' => true]);
Obviously a more complex solution would be needed if you needed to set multiple paths on the same result array, but this is the simplest solution for a single path.
Slightly different approach:
$var = array('a','an','asd','asdf');
$var2 = array_reverse($var);
$result = array('more_attributes' => true);
$temp = array();
foreach ($var2 as $val) {
$temp[$val] = $result;
$result = $temp;
$temp = array();
}

array conversion with in array PHP

i need to convert bellow array from
Array
(
[Property] => Array
(
[S] => Built As Condominium
)
)
to
Array
(
[property] => Built As Condominium
)
is their any way.
You could use an implode under a foreach
<?php
$arr=Array ( 'Property' => Array ( 'S' => 'Built As Condominium' ) );
foreach($arr as $k=>$arr1)
{
$arr[$k]=implode('',$arr1);
}
print_r($arr);
Demo
you can use the key of the array to implode the value in one line for example
$array['Property'] = $array['Property']['S'];
Results
Array ( [property] => Built As Condominium )
$data = array(
"Property" => array(
"S" => "Built As Condominium"
)
);
foreach($data as $key => $value) {
if($key == "Property") {
$normalized_data['Property'] = is_array($value) && isset($value['S']) ? $value['S'] : NULL;
}
}
Program Output
array(1) {
["property"]=>
string(20) "Built As Condominium"
}
Link
Implode is not necessary, or keys, just use a reference, i.e. the '&'. This is nice and simple.
$array = Array ( 'Property' => Array ( 'S' => 'Built As Condominium' ) );
foreach($array as &$value){
$value=$value['S'];
}
or.... if you don't know the key of the inner array but only care about its value (and assuming you want the first member of the inner array as your new value) then something like reset inside a foreach loop would work:
$arr = array ('Property' => array( 'S' => 'Built As Condominium'));
$new = array();
foreach($arr as $key => $inner) {
$new[$key] = reset($inner);
}
print_r($new);
output:
Array
(
[Property] => Built As Condominium
)

Flatten array joining keys with values

I have this multidimensional array:
$array = array(
'user1' => array('Miguel'),
'user2' => array('Miguel', 'Borges', 'João'),
'user3' => array(
'Sara',
'Tiago' => array('Male')
)
);
I want it flatten, transformed into:
$new_array = array(
'user1.Miguel',
'user2.Miguel',
'user2.Borges',
'user2.João',
'user3.Sara',
'user3.Tiago.Male',
);
Important:
The keys are very important to me. I want them concatenated,
separated by periods.
It should work with any level of nesting.
Thank you!
Though not explicitly stated in your question, it seems that you need to concatenate the string keys and ignore the integer keys (which may be easily achieved with is_string($key)). And since you need your code to “work with any level of nesting,” a recursive function would serve your purpose best:
function array_flatten_key($arr){
$_arr = array();
foreach($arr as $key => $val){
if(is_array($val)){
foreach(array_flatten_key($val) as $_val){
$_arr[] = is_string($key) ? $key.".".$_val : $_val;
}
}
else{
$_arr[] = is_string($key) ? $key.".".$val : $val;
}
}
return $_arr;
}
$new_array = array_flatten_key($array);
print_r($new_array);
The output will be:
Array
(
[0] => user1.Miguel
[1] => user2.Miguel
[2] => user2.Borges
[3] => user2.João
[4] => user3.Sara
[5] => user3.Tiago.Male
)

parsing out the last number of the post

Ok so i have a post that looks kind of this
[optional_premium_1] => Array
(
[0] => 61
)
[optional_premium_2] => Array
(
[0] => 55
)
[optional_premium_3] => Array
(
[0] => 55
)
[premium_1] => Array
(
[0] => 33
)
[premium_2] => Array
(
[0] => 36 )
[premium_3] => Array
(
[0] => 88 )
[premium_4] => Array
(
[0] => 51
)
how do i get the highest number out of the that. So for example, the optional "optional_premium_" highest is 3 and the "premium_" optional the highest is 4. How do i find the highest in this $_POST
You could use array_key_exists(), perhaps something like this:
function getHighest($variableNamePrefix, array $arrayToCheck) {
$continue = true;
$highest = 0;
while($continue) {
if (!array_key_exists($variableNamePrefix . "_" . ($highest + 1) , $arrayToCheck)) {
$continue = false;
} else {
highest++;
}
}
//If 0 is returned than nothing was set for $variableNamePrefix
return $highest;
}
$highestOptionalPremium = getHighest('optional_premium', $_POST);
$highestPremium = getHighest('premium', $_POST);
I have 1 question with 2 parts before I answer, and that is why are you using embedded arrays? Your post would be much simpler if you used a standard notation like:
$_POST['form_input_name'] = 'whatever';
unless you are specifically building this post with arrays for some reason. That way you could use the array key as the variable name and the array value normally.
So given:
$arr = array(
"optional_premium_1" => "61"
"optional_premium_2" => "55"
);
you could use
$key = array_keys($arr);
//gets the keys for that array
//then loop through get raw values
foreach($key as $val){
str_replace("optional_premium_", '', $val);
}
//then loop through again to compare each one
$highest = 0;
for each($key as $val){
if ((int)$val > $highest) $highest = (int)$val;
}
that should get you the highest one, but then you have to go back and compare them to do whatever your end plan for it was.
You could also break those into 2 separate arrays and assuming they are added in order just use end() http://php.net/manual/en/function.end.php
Loop through all POST array elements, pick out elements having key names matching "name_number" pattern and save the ones having the largest number portion of the key names. Here is a PHP script which does it:
<?php // test.php 20110428_0900
// Build temporary array to simulate $_POST
$TEMP_POST = array(
"optional_premium_1" => array(61),
"optional_premium_2" => array(55),
"optional_premium_3" => array(55),
"premium_1" => array(33),
"premium_2" => array(36),
"premium_3" => array(88),
"premium_4" => array(51),
);
$names = array(); // Array of POST variable names
// loop through all POST array elements
foreach ($TEMP_POST as $k => $v) {
// Process only elements with names matching "word_number" pattern.
if (preg_match('/^(\w+)_(\d+)$/', $k, $m)) {
$name = $m[1];
$number = (int)$m[2];
if (!isset($names[$name]))
{ // Add new POST var key name to names array
$names[$name] = array(
"name" => $name,
"max_num" => $number,
"key_name" => $k,
"value" => $v,
);
} elseif ($number > $names[$name]['max_num'])
{ // New largest number in key name.
$names[$name] = array(
"name" => $name,
"max_num" => $number,
"key_name" => $k,
"value" => $v,
);
}
}
}
print_r($names);
?>
Here is the output from the script:
Array
(
[optional_premium] => Array
(
[name] => optional_premium
[max_num] => 3
[key_name] => optional_premium_3
[value] => Array
(
[0] => 55
)
)
[premium] => Array
(
[name] => premium
[max_num] => 4
[key_name] => premium_4
[value] => Array
(
[0] => 51
)
)
)
Though ineffective, you could try something like
$largest = 0;
foreach($_POST as $key => $value)
{
$len = strlen("optional_premium_");
$num = substr($key, $len);
if($num > $largest)
$largest = $num;
}
print_r($largest);
The problem being that this will only work for one set of categories. It will most likely give errors throughout the script.
Ideally, you would want to reorganize your post, make each array be something like
[optional_premium_1] => Array
(
[0] => 61
["key"] => 1
)
[optional_premium_2] => Array
(
[0] => 61
["key"] => 2
)
Then just foreach and use $array["key"] to search.

Categories