How can I access to a nested objects - php

In the db:
{"49530fe2e872288d92042b3059f31566":{"filename":"49530fe2e872288d92042b3059f31566.jpg"},"4b7dc54328383c294ceb884e9691838c":{"filename":"4b7dc54328383c294ceb884e9691838c.jpg"}}
After using print:
Array (
[49530fe2e872288d92042b3059f31566] => Array (
[filename] => 49530fe2e872288d92042b3059f31566.jpg
)
[4b7dc54328383c294ceb884e9691838c] => Array (
[filename] => 4b7dc54328383c294ceb884e9691838c.jpg
)
)
How can I access filename?

Use foreach loop over the array to get filename.
<?php
$j = '{"49530fe2e872288d92042b3059f31566":{"filename":"49530fe2e872288d92042b3059f31566.jpg"},"4b7dc54328383c294ceb884e9691838c":{"filename":"4b7dc54328383c294ceb884e9691838c.jpg"}}';
$a = json_decode($j, TRUE);
if (! empty($a)) {
foreach ($a as $e) {
echo '<pre>';print_r($e['filename']);echo '</pre>';
}
}
?>

Use foreach loop if you are not aware of keys of array.
$arr = array (
'49530fe2e872288d92042b3059f31566' => array (
'filename' => '49530fe2e872288d92042b3059f31566.jpg'
),
'4b7dc54328383c294ceb884e9691838c' => array (
'filename' => '4b7dc54328383c294ceb884e9691838c.jpg'
)
); //To obtain this array from json , do **$arr = json_decode($json, true);**
foreach($arr as $val){
$filename = $val['filename']; //There you go
}

Related

PHP Group keys of associative array by values

function groupByOwners(array $files) : array { return []; }
$files = array("Input.txt" => "Randy","Code.py" => "Stan","Output.txt" =>"Randy");
Print_r(groupByOwners($files);
My expected output is:
[Randy => [Input.txt, Output.txt] , Stan => [Code.py]]
You just need to iterate over your array, pushing each filename to a new array indexed by the names:
function groupByOwners(array $files) : array {
$output = array();
foreach ($files as $file => $name) {
$output[$name][] = $file;
}
return $output;
}
$files = array("Input.txt" => "Randy","Code.py" => "Stan","Output.txt" =>"Randy");
print_r(groupByOwners($files));
Output:
Array
(
[Randy] => Array
(
[0] => Input.txt
[1] => Output.txt
)
[Stan] => Array
(
[0] => Code.py
)
)
Demo on 3v4l.org

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

Convert Multi dimensional array PHP

I want to convert multi dimensional array in Php
I'm stuck in logic.. Kindly help
Thanks in advance
Current Produced array :
Array
(
[5316] => Array
(
[0] => Array
(
[PROD1] => color=black
)
[1] => Array
(
[PROD1] => paper=a1
)
[2] => Array
(
[PROD2] => color=metallic_silver
)
[3] => Array
(
[PROD2] => paper=a1
)
)
)
I want to convert this array into this form
Array
(
[5316] => Array
(
[PROD1] => Array
(
color => black
paper => a1
)
[PROD2] => Array
(
color => metallic_silver
paper => a1
)
)
)
If you can't hardcode that key to directly point to it, you can use reset() in this case, then grouped them inside a foreach accordingly. Example:
$array = array(
5316 => array(
array('PROD1' => 'color=black'),
array('PROD1' => 'paper=a1'),
array('PROD2' => 'color=metallic_silver'),
array('PROD2' => 'paper=a1'),
),
);
$grouped = array();
// point it to the first key which gives an array of those values
foreach (reset($array) as $key => $value) {
reset($value); // reset the internal pointer of the sub array
$key = key($value); // this return `PROD1, PROD2`
$grouped[$key][] = current($value); // current gives color=black, the values
}
$array[key($array)] = $grouped; // then reassign
echo '<pre>';
print_r($array);
Sample Output
You can try something like below.
$newArr = [];
$count = count($arr[5316]);
for($i = 0, $j = 1; $i < $count; $i += 2){
$color = explode('=', $arr[5316][$i]['PROD'.$j]);
$paper = explode('=', $arr[5316][$i+1]['PROD'.$j]);
$newArr[5316]['PROD'.$j] = array('color'=>$color[1], 'paper'=>$paper[1]);
$j++;
}
//To show output
print '<pre>';
print_r($newArr);
print '</pre>';

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
)

Convert an array of strings, each string has dot separated values, to a multidimensional array

I have the following array:
Array
(
[0] => INBOX.Trash
[1] => INBOX.Sent
[2] => INBOX.Drafts
[3] => INBOX.Test.sub folder
[4] => INBOX.Test.sub folder.test 2
)
How can I convert this array to a multidimensional array like this:
Array
(
[Inbox] => Array
(
[Trash] => Array
(
)
[Sent] => Array
(
)
[Drafts] => Array
(
)
[Test] => Array
(
[sub folder] => Array
(
[test 2] => Array
(
)
)
)
)
)
Try this.
<?php
$test = Array
(
0 => 'INBOX.Trash',
1 => 'INBOX.Sent',
2 => 'INBOX.Drafts',
3 => 'INBOX.Test.sub folder',
4 => 'INBOX.Test.sub folder.test 2',
);
$output = array();
foreach($test as $element){
assignArrayByPath($output, $element);
}
//print_r($output);
debug($output);
function assignArrayByPath(&$arr, $path) {
$keys = explode('.', $path);
while ($key = array_shift($keys)) {
$arr = &$arr[$key];
}
}
function debug($arr){
echo "<pre>";
print_r($arr);
echo "</pre>";
}
I was very interested in this as was having immense difficulty trying to do this. After looking at (and going through) Jon's solution I have come up with this:
$array = array();
function parse_folder(&$array, $folder)
{
// split the folder name by . into an array
$path = explode('.', $folder);
// set the pointer to the root of the array
$root = &$array;
// loop through the path parts until all parts have been removed (via array_shift below)
while (count($path) > 1) {
// extract and remove the first part of the path
$branch = array_shift($path);
// if the current path hasn't been created yet..
if (!isset($root[$branch])) {
// create it
$root[$branch] = array();
}
// set the root to the current part of the path so we can append the next part directly
$root = &$root[$branch];
}
// set the value of the path to an empty array as per OP request
$root[$path[0]] = array();
}
foreach ($folders as $folder) {
// loop through each folder and send it to the parse_folder() function
parse_folder($array, $folder);
}
print_r($array);

Categories