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];
Related
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
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'm new to PHP so I'm not sure how to optimize this code.
I execute a Python script from PHP and the $output variable returned is an array of arrays.
exec (" /Users/$USER/anaconda/bin/python /Applications/MAMP/cgi-bin/Evaluation1.py",$output)
Each array within the $output array contains one string value separated by commas. So $output is Array ( [0] => 1, 好, 0 [1] => 2, 妈妈, 3), etc.
In each array within the $output array, I use explode on the string value to create an array, and add it to my new $output array called $output2
$output2 = array();
foreach($output as $value){
$myArray = explode(',', $value);
$output2[] = $myArray;
}
Is there a way to just replace/overwrite the string value in the arrays within $output with the new array, instead of adding each item to a new $output2 array?
You could use array_walk to do the loop over output. You pass in a callback function that is called for each value by reference so any changes to the passed in value stick to the array.
Test data:
$output = array(
'1,A,2',
'2,B,3',
'3,C,4'
);
PHP >= 5.3.0
array_walk($output, function(&$val){ $val = explode(',', $val); } );
Older PHP
function mySplit(&$val){
$val = explode(',', $val);
}
array_walk($output, 'mySplit');
Both output:
Array
(
[0] => Array
(
[0] => 1
[1] => A
[2] => 2
)
[1] => Array
(
[0] => 2
[1] => B
[2] => 3
)
[2] => Array
(
[0] => 3
[1] => C
[2] => 4
)
)
Some great answers already. Just adding this for completeness.
$ar = array(
"1,2,3",
"4,5,6"
);
foreach($ar as $k => $v) {
$ar[$k] = explode(',', $v);
}
Wold be interesting to see a a performance difference of the different methods although i doubt it would be much.
I have 5 different array whose structure is :-
Array ( [0] => http://www.php.net/200
)
Array ( [0] => http://www.php.net/?setbeta=1&beta=1302
)
Array ( [0] => http://www.php.net/downloads.php200
)
Array ( [0] => http://www.php.net/docs.php200
)
Array ( [0] => http://www.php.net/FAQ.php302
)
I need to merge these all in a single array whose structure would be like:-
Array ( [0] => http://www.php.net/200
[1] => http://www.php.net/?setbeta=1&beta=1302
[2] => http://www.php.net/downloads.php200
[3] => http://www.php.net/docs.php200
[4] => http://www.php.net/FAQ.php302
)
One thing i want to confirm that these arrays are forming inside a loop function and it could be of any number and also they have a single name i.e $array
Simplest is probably just array_merge().
$merged = array_merge( $ar1, $ar2, $ar3, $ar4, $ar5 );
Use array_merge.
$arr = array_merge($arr1,$arr2,$arr3,$arr4,$arr5);
Edit After seeing your comment, you are having multidimensional array.
$arr = array();
for($i = 0; $i < $old_arr; $i++) {
$arr[] = $old_arr[$i][0];
}
Use array_merge
$arr1=Array ( 0 => 'http://www.php.net/200');
$arr2=Array( 0 => 'http://www.php.net/?setbeta=1&beta=1302');
$arr3=Array( 0 => 'http://www.php.net/downloads.php200');
$merged=array_merge($arr1,$arr2,$arr3);
print_r($merged);
$newarray = array();
while ( is_array( array_get_function_here() ) )
{
$newarray = array_merge( $newarray, $array );
}
I would try that if you get the different arrays in a looping function.
The above $array is something that array_get_function_here() should return for the while loop validity check (if it returns and array, the while check runs as true). array_get_function_here() is just an example and should be some function that returns a value for $array.
This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 1 year ago.
Here's a section my multidimensional array:
Array (
[0] => Array ( [0] => Height [1] => 40 )
[1] => Array ( [0] => Weight [1] => 15 )
[2] => Array ( [0] => Ctr_Percent [1] => 15 )
)
What would the syntax be for just printing height, weight, and ctr_percent? I don't mean echoing it like:
echo $array[0][0];
echo $array[1][0];
Is there a way to iterate through the entire multidimensional array and echo out the first value of each child array?
Supposing you use php 5.3:
$first_elements = array_map(function($i) {
return $i[0];
}, $data);
Otherwise you need to implement a callback function or just use plain old foreach
Here is a one-liner:
array_map('array_shift', $array);
Will return:
Array
(
[0] => Height
[1] => Weight
[2] => Ctr_Percent
)
And here is another one:
array_combine(array_map('array_shift', $temp), array_map('array_pop', $temp))
Will return:
Array
(
[Height] => 40
[Weight] => 15
[Ctr_Percent] => 15
)
Use array_column:
$result = array_column($array, 0);
foreach ($main_array as $inner_array){
echo $inner_array[0] . "\n";
}
foreach($array as $x) {
echo $x[0]."\n";
}
I think the function your looking for is reset() e.g.
array_map('reset', $array);
or
foreach ($array as $subarray)
echo reset($subarray)."\n";
Note that this works even if 0 is not the first index of the array. E.g. $a = [1=>5,0=>3]; echo reset($a); would still echo 5;.
The easiest way to do it using array_walk
function getFirstElement(&$val){
$val = $val[0];
}
array_walk($data,'getFirstElement');
Now if you print $data like print_r($data); you will get result as below
Array
(
[0] => Height
[1] => Weight
[2] => Ctr_Percent
)