I have an array that can have many values at any given point, what I would like to accomplish is to combine all the array indexes and form one index with my final value. Merge other values that are the same
Say I have the array result below
Array
(
[0] => stdClass Object
(
[component] => sodium chloride
[generic_results] => Average:=99.20%
)
[1] => stdClass Object
(
[component] => sodium chloride
[generic_results] => RSD:=0.54%
)
[2] => stdClass Object
(
[component] => sodium chloride
[generic_results] => n:=3
)
)
What I would like is something like this
Array
(
[0] => stdClass Object
(
[component] => sodium chloride
[generic_results] => Average:=99.20%,RSD:=0.54%, n:=3
)
)
I have tried array unique but its not working.
Example code generating the results:
$arr=array(
(object) array(
'component'=>'sodium chloride',
'generic_results'=>'Average:=99'
),
(object) array(
'component'=>'sodium chloride',
'generic_results'=>'RSD:=0.54'
),
(object) array(
'component'=>'sodium chloride',
'generic_results'=>'n:=3'
)
);
print('<pre>');
print_r($arr);
print('</pre>');
Any Suggestions for this problem?
Try this
$new = array();
foreach ($array as $obj){
// By setting the key you guarantee it being unique
$new[$obj->component][$obj->generic_results] = $obj->generic_results;
}
$new2 = array();
foreach ($new as $comp=>$arr){
$new2['component'][$comp] = implode(',',$arr);
}
This will return an array but you can (although its not always sufficient) then use json_decode(json_encode($new2), false) to convert it to the object. Hope that helps.
You can use array_reduce, which iterates over an array to combine all elements with a given callback function:
$result = array_reduce($arr, function($result, $item) {
if ($result === null) {
// initialize with first item
return [$item];
}
// add generic_results of current item to result
$result[0]->generic_results .= ',' . $item->generic_results;
return $result;
}
);
Demo: https://3v4l.org/KBUBl
Related
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
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();
}
Assuming that I have an array of objects like this:
Array
(
[0] => stdClass Object
(
[id] => 10-423-1176
[qty] => 2
[price] => 12.6
)
[1] => stdClass Object
(
[id] => 26-295-1006
[qty] => 24
[price] => 230.35
)
[2] => stdClass Object
(
[id] => 12-330-1000
[qty] => 2
[price] => 230.35
)
And I have another array of object hat looks like this:
Array
(
[0] => Item Object
(
[internalId] => 14062
[itemVendorCode] => 89-605-1250
)
[1] => Item Object
(
[internalId] => 33806
[itemVendorCode] => 89-575-2354
)
[2] => Item Object
(
[internalId] => 64126
[itemVendorCode] => 26-295-1006
)
)
I want to loop through the 2nd array of objects and get the 'itemVendorCode' and then use it as the 'id' to get the object from the first array of objects. Is there a way to obtain what I want without looping the first array? Looping is very costly in my use-case.
You will have to use loops in any case, even if those loops are hidden within PHP built-in functions.
For instance:
$codes = array_map(function ($item) { return $item->itemVendorCode; }, $array2);
$items = array_filter($array1, function ($item) use ($codes) { return in_array($item->id, $codes); });
// $items contains only elements from $array1 that match on $array2
If this will be more efficient than using regular loops is hard to tell.
Since you are aparently trying to code what is supposed to be a DBMS's job, I recommend you export those tables to a database server such as MySQL instead and let it work its magic on those "JOINs".
Answering your comment, you could merge with something like this:
$result = array();
foreach ($array1 as $item1)
foreach ($array2 as $item2)
if ($item1->id == $item2->itemVendorCode)
$result[] = (object)array_merge((array)$item1, (array)$item2));
$result will contain a new set of objects that merge properties from both $array1 and $array2 where they intersect in id == itemVendorCode.
Do you need first arrays index keys? if not you could iterate throuh first array once and set key to id. Something like:
foreach ($items as $key => $item) {
$items[$item->id] = $item;
unset($items[$key]);
}
Here is another direct approach to solve this problem, even better than the one I proposed earlier:
// you got the $itemVendorCode from looping through the second array, let say :
$itemVendorCode = "89-605-1250";
// I'm assuming that you converted the array of objects in into accessible multidimensional array
// so the $first_array would look like :
$first_array= array (
array (
"id" => "10-423-1176",
"qty" => 2,
"price" => 12.6
),
array (
"id" => "10-423-1176",
"qty" => 5,
"price" => 25
),
array (
"id" => "89-605-1250",
"qty" => 12,
"price" => 30
)
);
// Now you can filter the first array using
$filter = function ($player) use($itemVendorCode) {
return $player ['id'] == $itemVendorCode;
};
$filtered = array_filter ( $first_array, $filter );
// print the price of the matching filtered item
print $filtered[key($filtered)]['price'] ;
You can use the array_map and array_filter() function to achieve that.
Try with this code:
<?php
$first = array();
$first[0] = new stdClass;
$first[0]->id = '89-605-1250';
$first[0]->qty = 2;
$first[0]->price = 12.6;
$first[1] = new stdClass;
$first[1]->id = '89-575-2354';
$first[1]->qty = 24;
$first[1]->price = 230.35;
$last = array();
$last[0] = new stdClass;
$last[0]->internalId = 14062;
$last[0]->itemVendorCode = '89-605-1250';
$last[1] = new stdClass;
$last[1]->internalId = 33806;
$last[1]->itemVendorCode = '89-575-2354';
$ids = array_map(function($element){return $element->itemVendorCode;}, $last);
$to_find = $ids[0];
$object = array_filter($first, function($element){global $to_find; return $element->id == $to_find ? true: false;})[0];
print_r($object);
?>
Output:
stdClass Object
(
[id] => 89-605-1250
[qty] => 2
[price] => 12.6
)
try using array_search:
http://php.net/manual/en/function.array-search.php
foreach($array2 as $key=>$item) {
$firstArrayObjectKey = array_search($item['itemVendorCode'], $array1);
//... do something with the key $firstArrayObjectKey
}
In this case you'll need to loop through the first array to get the itemVendorCode.
Right after that you can use the itemValue you got from the previous process to search in a reduced array of the first object using array_reduce function:
http://php.net/manual/en/function.array-reduce.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
)
I'm trying to use a specific object type from a JSON feed, and am having a hard time specifying it. Using the code below I grab and print the specific array (max) I want,
$jsonurl = "LINK";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json,true);
$max_output = $json_output["max"];
echo '<pre>';
print_r($max_output);
echo '</pre>';
And from the Array below, all I want to work with is the [1] objects in each array. How can I specify and get just those values?
Array
(
[0] => Array
(
[0] => 1309924800000
[1] => 28877
)
[1] => Array
(
[0] => 1310011200000
[1] => 29807
)
[2] => Array
(
[0] => 1310097600000
[1] => 33345
)
[3] => Array
(
[0] => 1310184000000
[1] => 33345
)
[4] => Array
(
[0] => 1310270400000
[1] => 33345
)
[5] => Array
(
[0] => 1310356800000
[1] => 40703
)
Well you could fetch those values with array_map:
$max_output = array_map(function($val) { return $val[1]; }, $json_output["max"]);
This requires PHP 5.3, if you use an earlier version, then you can use create_function to achieve similar results:
$max_output = array_map(create_function('$val', 'return $val[1];'), $json_output["max"]);
When you need to create new array which will contain only second values, you may use either foreach loop which will create it or use array_map() (just for fun with anonymous function available since php 5.3.0):
$newArray = array_map( function( $item){
return $item[1]
},$array);
Then you want to use last ("max" -> considering array with numeric keys) item, you can use end():
return end( $item);
And when you can process your data sequentially (eg. it's not part of some big getData() function) you can rather use foreach:
foreach( $items as $key => $val){
echo $val[1] . " is my number\n";
}
After you get $max_output...
for( $i = 0; $i < length( $max_output ); $i++ ) {
$max_output[$i] = $max_output[$i][1];
}
try this:
$ones = array();
foreach ($max_output as $r)
$ones[] = $r[1];