Ok, so I have this in a JSON array (the output of retrievedData())
{
"device": {
"01AA02AB141208VV": {
"$version": -148598935,
"$timestamp": 1344382016000,
"serial_number": "01AA02AB141208VV"
}
}
}
However, I can't seem to select the serial number. I have tried what usually works, but I can't select it. This is assuming we don't already know the "01AA02AB141208VV".
$retrieved_data = retrieveData($array['userid'], $array['urls']['transport_url'], $array['access_token']);
$retrieved_data_array = json_decode($retrieved_data, true);
$serial_number = $retrieved_data_array['device'][0]['serial_number'];
Am I doing something wrong? I bet it's really simple, but I just cannot figure it out!
Thanks!
Unfortunately, it's not really simple. You're trying to find 42 Main St. when you don't know the city Main St. is located in. The only way to find the serial_number would be to loop over $retrieved_data_array with foreach until you find the value you want.
you can use key() function to access the keys of the associative array (in this case the '$retrieved_data_array['device']' array:
<?php
$data = '{"device": {"01AA02AB141208VV": {"$version": -148598935,"$timestamp": 1344382016000,"serial_number": "01AA02AB141208VV"}}}';
$retrieved_data_array = json_decode($data, true);
$serial_number = key($retrieved_data_array['device']);
reset($retrieved_data_array['device']);
print_r($serial_number);
print_r($retrieved_data_array['device'][$serial_number]);
?>
This will grab the serial numbers, assuming you have multiple items in the devices array:
$keys = array();
foreach( $retrieved_data_array['device'] as $key => $val ){
$keys[] = $key;
}
$serial = $keys[0];
This can be reduced if you know you only have one item in the array...
Related
I have an array that looks like this:
Id = "ADA001"
Stock: 15
The array has about 1700 records that looks the same, how would I search the array for the ID 1 and return the stock?
Edit: I will need to access the stock of each one of these 17000 records
Edit: I have been getting some help from Daniel Centore, he told me to set an arrays primary key to the id of the item and that it is equal to the stock, but I can't get it to work.
I am currently getting the data from an MySQL database and I store it in an array, like so:
$data[] = array();
$getdisposabletest = mysqli_query($connect, "Select id, disposable FROM products");
while ($z = mysqli_fetch_array($getdisposabletest)) {
$data = $z;
}
Now when I use Daniels code that looks like this:
$myMap = [];
foreach($data as $item) {
$myMap[$item['id']] = $item['disposable'];
}
It doesn't return anything when I try to echo my product with the ID "ADA001"
echo $myMap["ADA001"];
Also when I do "count($mymap)" it says its 2 records big, when it should be muuuch larger than that?
Thanks for help
I would use array_filter. Return the result of a comparitor.
$results = array_filter($targetArray, function($el) {
return $el === 1;
});
Edit: Now that it has been made clear that the OP wants to query from thousands of items, the correct way to do this is to make the Id the key to a map in PHP, like this:
$myMap = [];
foreach($array as $item) {
$myMap[$item['Id']] = $item['Stock'];
}
Now, whenever you want to access item '12', simply use $myMap['12'].
The reason this is faster is because of something called algorithmic complexity. You should read about Big-O notation for more info. Essentially, the first operation here is on the order of n and then looping through each of the items that comes out is on the order of n*log(n), so the final result is on the order of n*log(n) which is the best you'll be able to do without more information. However, if you were only accessing one element, just accessing that one element via MySQL would be better because it would be on the order of log(n), which is faster.
Edit 2: Also notice that if you were to access mutliple fields (ie not just the stock) you could do the following:
$myMap = [];
foreach($array as $item) {
$myMap[$item['Id']] = $item;
}
And simply access item 12's stock like this: $myMap['12']['stock'] or its name like this: $myMap['12']['name'].
You would do something like this.
$newArray=[];
foreach($array as $item){
if($item['Id'] === 1){
$newArray[] = $item;
}
}
$stockArray = array_column($newArray,'Stock');
I know this should be very simple, but boy I'm making a mess of it... would be great if someone could point me in the right direction.
I've got an array which looks like this:
print_r($request_attributes['length']);
Array
(
[0] => 28.00000
[1] => 18.00000
)
and am trying to modify like so:
if(is_array($request_attributes['length'])) {
$request_attributes['length'] = $request_attributes['length'][0];
print($request_attributes['length']);
$request_attributes['length'] = $request_attributes['length'][1];
print($request_attributes['length']);
}
which gives the correct output in the first update, but the second item outputs an '8'. I've tried the above in both a for and foreach which results in similar output for both this and the other two arrays ( width(8) and height(0) - they should result in 18.00000 and 13.00000 respectively ). So I guess I really have two questions:
1. How do I update this(these) element(s)?
2. Where are the funny outputs actually coming from?
If anyone can help, I'd really appreciated it.
Just have a look at this. Your problem is, that you override you variable and in the second step $request_attributes['length'] is a string. Just define another var for your values.
$request_attributes['length'] = [
28.000,
18.000
];
$attributes = array();
if (is_array($request_attributes['length'])) {
foreach ($request_attributes['length'] as $value) {
$attributes[] = $value;
}
}
As you see $attributes will contain all values of your $request_attributes['length'] array and will not be overwritten.
Define araay as below
$val=array([0]=>"18.000",[1]=>13.000)
then use
if(is_array($request_attributes['length'])) {
$request_attributes['length'] = $val;
print_r($request_attributes['length']);
$request_attributes['length'] = $val;
print_r($request_attributes['length']);
}
Previously your array doesnt have any name.
Your print will only return Just array not the values
use
print_r($request_attributes['length']) ;
instead
<?php
$interests[50] = array('fav_beverages' => "beer");
?>
now i need the index (i.e. 50 or whatever the index may be) from the value beer.
I tried array_search(), array_flip(), in_array(), extract(), list() to get the answer.
please do let me know if I have missed out any tricks for the above functions or any other function I`ve not listed. Answers will be greatly appreciated.
thanks for the replies. But for my disappointment it is still not working. btw I have a large pool of data like "beer");
$interests[50] = array('fav_cuisine' => "arabic");
$interests[50] = array('fav_food' => "hummus"); ?> . my approach was to get the other data like "arablic" and "hummus" from the user input "beer". So my only connection is via the index[50].Do let me know if my approach is wrong and I can access the data through other means.My senior just informed me that I`m not supposed to use loop.
This should work in your case.
$interests[50] = array('fav_beverages' => "beer");
function multi_array_search($needle, $interests){
foreach($interests as $interest){
if (array_search($needle, $interest)){
return array_search($interest, $interests);
break;
}
}
}
echo multi_array_search("beer", $interests);
If your array contains multiple sub-arrays and you don't know which one contains the value beer, then you can simply loop through the arrays, and then through the sub-arrays, to search for the value, and then return the index if it is found:
$needle = 'beer';
foreach ($interests as $index => $arr) {
foreach ($arr as $value) {
if ($value == $needle) {
echo $index;
break;
}
}
}
Demo
If i knew the correct terms to search these would be easy to google this but im not sure on the terminology.
I have an API that returns a big object. There is one particular one i access via:
$bug->fields->customfield_10205[0]->name;
//result is johndoe#gmail.com
There is numerous values and i can access them by changing it from 0 to 1 and so on
But i want to loop through the array (maybe thats not the correct term) and get all the emails in there and add it to a string like this:
implode(',', $array);
//This is private code so not worried too much about escaping
Would have thought i just do something like:
echo implode(',', $bug->fields->customfield_10205->name);
Also tried
echo implode(',', $bug->fields->customfield_10205);
And
echo implode(',', $bug->fields->customfield_10205[]->name);
The output im looking for is:
'johndoe#gmail.com,marydoe#gmail.com,patdoe#gmail.com'
Where am i going wrong and i apologize in advance for the silly question, this is probably so newbie
You need an iteration, such as
# an array to store all the name attribute
$names = array();
foreach ($bug->fields->customfield_10205 as $idx=>$obj)
{
$names[] = $obj->name;
}
# then format it to whatever format your like
$str_names = implode(',', $names);
PS: You should look for attribute email instead of name, however, I just follow your code
use this code ,and loop through the array.
$arr = array();
for($i = 0; $i < count($bug->fields->customfield_10205); $i++)
{
$arr[] = $bug->fields->customfield_10205[$i]->name;
}
$arr = implode(','$arr);
This is not possible in PHP without using an additional loop and a temporary list:
$names = array();
foreach($bug->fields->customfield_10205 as $v)
{
$names[] = $v->name;
}
implode(',', $names);
You can use array_map function like this
function map($item)
{
return $item->fields->customfield_10205[0]->name;
}
implode(',', array_map("map", $bugs)); // the $bugs is the original array
Please i want to loop through my table and compare values with an array in a php included file. If there is a match, return the array key of the matched item and replace it with the value of the table. I need help in returning the array keys from the include file and comparing it with the table values.
$myarray = array(
"12aaa"=>"hammer",
"22bbb"=>"pinchbar",
"33ccr"=>"wood" );
in my loop in a seperate file
include 'myarray.inc.php';
while($row = $db->fetchAssoc()){
foreach($row as $key => $val)
if $val has a match in myarray.inc.php
{
$val = str_replace($val,my_array_key);
}
}
So in essence, if my db table has hammer and wood, $val will produce 12aaa and 3ccr in the loop. Any help? Thanks a lot
You are looking for array_search which will return the key associated with a given value, if it exists.
$result = array_search( $val, $myarray );
if ($result !== false) {
$val = $result;
}
your array should look like
$myarray = array(
"hammer"=>"11aaa",
"pinchbar"=>"22bbb",
"wood"=>"33ccr" );
and code
if (isset($myarray[$key])){
//do stuff
}
I think you need the function in_array($val, $myarray);
If you don't want or can't change $myarray structure like #genesis proposed, you can make use of array_flip
include 'myarray.inc.php';
$myarray = array_flip($myarray);
while($row = $db->fetchAssoc()) {
foreach($row as $key => $val) {
if (isset($myarray[$val])) {
// Maybe you should use other variable instead of $val to avoid confusion
$val = $myarray[$val];
// Rest of your code
}
}
}