Retrieving correct record from multidimentional array - php

I'm having a mental freeze moment. If I have an array in the following format:
$myData = Array
(
[0] => stdClass Object
(
[id] => 1
[busID] => 5
[type] => SMS
[number] => 5128888888
)
[1] => stdClass Object
(
[id] => 2
[busID] => 5
[type] => APP
[number] => 5125555555
)
[2] => stdClass Object
(
[id] => 4
[busID] => 5
[type] => APP
[number] => 5129999988
[verified] => 1
[default] => 0
)
)
And I only have an var for ID of the record, how do I retrieve the rest of the detail for that set.
$myID = 2;
// get number 5125555555 and it's type
echo $myData[][$myID]['number']; // ???

The way you have your data arranged your going to have to loop through your array to identify the object corresponding to $myID.
foreach($myData as $object) if($object->id == $myID) echo $object->number;
The alternative is to arrange your $myData as an associative array with the id field as the key. Then you could access it simply with $myData[$myID]->number.

Actually it's an array that contains StdClass objects , try looping over $myData and access each attribute :
foreach ( $myData as $data )
{
print_r($data->id);
// ...
}

You can avoid loop by using following logic:
<?php
$myID = 2;
$myData = json_decode(json_encode($myData),1); // Convert Object to Array
$id_arr = array_column($myData, 'id'); // Create an array with All Ids
$idx = array_search($myID, $id_arr);
if($idx !== false)
{
echo $myData[$idx]['type'] . ' -- ' . $myData[$idx]['number'];
}
?>
Working Demo
Note: array_column is supported from PHP 5.5.
For lower versions you can use this beautiful library https://github.com/ramsey/array_column/blob/master/src/array_column.php

You can create a custom function to achieve this, you need to pass the array and id whose details you want and the function will return the array with matching id, like below
function detailsById($myData,$id){
foreach($myData as $data){
if($data->id == $id){
return $data;
}
}
}
Just call this function with your array and id..
$data=detailsById($myData,2);
echo "<pre>";print_r($data);
This will give you :
stdClass Object
(
[id] => 2
[busID] => 5
[type] => APP
[number] => 5125555555
)
And further to print 'number' and 'type' use $data array
$data['type'];
$data['number'];

Related

How to search value by specific keyword in array of objects and get it in Laravel?

How to search an array of objects by keyword and get that object set if exists.
For example --
array(
[0] => Object
(
[id] => 123
[label] => 'Jone Due'
[title] => 'Bangladeshi Laravel Expert'
)
[1] => Object
(
[id] => 234
[label] => 'Jone Due'
[title] => 'Bangladeshi Singer'
)
[2] => Object
(
[id] => 345
[label] => 'Jone Due'
[title] => 'Bangladeshi Actor'
)
....
);
I want to search title with keyword Laravel, and result i want to get --
array(
[0] => Object
(
[id] => 123
[label] => Jone Due
[title] => Bangladeshi Laravel Expert
)
);
Is it possible?
Try next. It works for me:
$i = 0; // counter
$ar = []; // array of indexes of success objects
$ar2 = []; // result array of objects which title has 'Laravel' inside
// $obj_ar must be consists of objects (it should has some checking code for that requirement)
// filling an array of indexes $ar
foreach ($obj_ar as $obj_1){
if (strstr($obj_1->title,'Laravel')) array_push ($ar, $i);
$i++;
}
// building a result array of objects
$count_ar = count($ar);
if ($count_ar>0) {
for($o = 0; $o < $count_ar; $o++){
array_push ($ar2, $obj_ar[$o]);
}
}
// result array of objects
echo '<pre>';
print_r($ar2);
echo '</pre>';
or a bit faster way:
$i = 0; // counter
$ar2 = []; // result array of objects which title has 'Laravel' inside
// $obj_ar must be consists of objects (it should has some checking code for that requirement)
// filling an array of indexes $ar
foreach ($obj_ar as $obj_1){
if (strstr($obj_1->title,'Laravel')) array_push ($ar2, $obj_ar[$i]);
$i++;
}
// result array of objects
echo '<pre>';
print_r($ar2);
echo '</pre>';

How to get the single value from the array? [duplicate]

I stored some data to an array using this code
$this->data['result'] = $this->mymodel->search($keyword);
when I print my result by using print_r($this->data);
it shows like this
Array ( [base_url] => http://localhost/pelikanartline.com/ [result] => Array ( [0] => stdClass Object ( [product_id] => 2 [product_code] => 167007 [product_name] => ARTLINE VIVIX HIGHLIGHTERS 10PK YELLOW [product_discription] => some description [xylene_free] => y [rohs_compliant] => y [product_features] => some text ) ) )
now I want to store product_id value to a variable like pro_id. please help me to do this.
Try this:
$pro_id = [];
foreach($this->data['result'] as $key => $val){
$pro_id[] = $val->product_id;
}
print_r($pro_id);
If your model returns only one record, you can use this shortcut:
$pro_id = $this->data['result'][0]->product_id;

Extracting a property from an array of an array of objects

I've got an object, containing an array of objects, containing an array of values:
stdClass Object (
[devices] => Array (
[0] => stdClass Object (
[location] => 1
[delegate] =>
[type] => 1
[id] => 1234
[IP] => 1.2.3.4
[name] => host1
[owner] => user6
[security] => 15
)
[1] => stdClass Object (
[location] => 2
[delegate] =>
[type] => 1
[id] => 4321
[IP] => 4.3.2.1
[name] => host2
[owner] => user9
[security] => 15
)
)
)
I want to extract just the id and name into an array in the form of:
$devices['id'] = $name;
I considered using the array_map() function, but couldn't work out how to use it... Any ideas?
This will generate you a new array like I think you want
I know you says that delegate is an object but the print does not show it that way
$new = array();
foreach($obj->devices as $device) {
$new[][$device->id] = $device->name;
}
Would something like this not work? Untested but it cycles through the object structure to extract what I think you need.
$devices = myfunction($my_object);
function myfunction($ob){
$devices = array();
if(isset($ob->devices)){
foreach($ob->devices as $d){
if(isset($d->delegate->name && isset($d->delegate->id))){
$devices[$d->delegate->id] = $d->delegate->name;
}
}
}
return($devices);
}
Im usually using this function to generate all child and parent array stdclass / object, but still make key same :
function GenNewArr($arr=array()){
$newarr = array();
foreach($arr as $a=>$b){
$newarr[$a] = is_object($b) || is_array($b) ? GenNewArr($b) : $b ;
}
return $newarr;
}

PHP Help to simplify an IF statement when retrieving results from a function

Let's say i have this function that seeks for a value inside a bidimensional array:
function findValueBi($array, $field, $value, $returnfield)
{
foreach($array as $key => $product)
{
if ( $product[$field] === $value )
return $product[$returnfield];
}
return false;
}
And the bidimensional array looks like this:
Array
(
[0] => Array
(
[number] => 2
[type] => unimodal
)
[1] => Array
(
[number] => 6
[type] => unimodal
)
[2] => Array
(
[number] => 8
[type] => multimodal
)
[3] => Array
(
[number] => 27
[type] => multimodal
)
[4] => Array
(
[number] => 29
[type] => multimodal
)
)
What the function does, is to look for a given value inside the 'number' key. If it's found, i retrieve its corresponding 'type' key value. For example, if i am looking for the 'number' 29, then i will get the 'type' value "multimodal" (the last item of the array sample). Otherwise, if the value is not found, the function returns false.
So, the way i retrieve this value is as follows:
if(findValueBi($numbers_patterns,'number',$number,'type')!==false){
$resultado=findValueBi($numbers_patterns,'number',$number,'type');
return $resultado;
}
else{ ... }
Is there a better and/or faster way to do this? Is it possible to retrieve the info right inside the if statement? As you can see, I am calling the function twice, so how can i call it once with the if statement???
You could just elect to use it the first time, then use it inside the if:
$resultado = findValueBi($numbers_patterns,'number',$number,'type'); // call it once
if($resultado !== false){
// use $resultado here
}

CakePHP Model Query Return Data Formating

I'm looking for a way to make it so cake returns all database data in the same format/structure... Currently it returns two different types of format depending on the relationship.
If a model 'B' is associated with the current model 'A' being queried it will then place model associations for 'B' underneath it as you can see in [User] below. I want it so that all queries use that structure.
example:
$this->find('all', ....
returns:
Array
(
[0] => Array
(
[UserGroup] => Array
(
[id] => 53
[user_id] => 100003332014851
[media_id] =>
[name] => john
[description] => qwasdfad
)
[User] => Array
(
[id] => 100003332014851
[session_id] => ssm2qbrotmm13ho1ipm8ii2492
[username] =>
[password] => -1
[Planner] => Array
(
)
[Purchase] => Array
(
)
[Listing] => Array
(
)
)
)
I want this to look like:
Array
(
[0] => Array
(
[UserGroup] => Array
(
[id] => 53
[user_id] => 100003332014851
[media_id] =>
[name] => john
[description] => qwasdfad
[User] => Array
(
[id] => 100003332014851
[session_id] => ssm2qbrotmm13ho1ipm8ii2492
[username] =>
[password] => -1
[Planner] => Array
(
)
[Purchase] => Array
(
)
[Listing] => Array
(
)
)
)
)
)
In CakePHP, the find() method return data like your first format. But If you want to format like second one then you have to process it by hand (try to avoid this if possible)
$data = $this->find('all');
$assocs = Set::extract('/User', $data); // extracting all `User` array
foreach($assocs as $key => $assoc) {
unset($data[$key]['User']); // removing the associate `User` from `$data`
$data[$key]['UserGroup']['User'] = $assoc['User']; // adding associate under `UserGroup`
}
ended up doing this... it changes the output to what we need. The top level item does not have a header which is fine I just adjusted our scripts for that... maybe this will help somebody else if they need a custom idea
also no guarantee this covers all possible results but so far it works with all the queries we have.
class AppModel extends Model {
function afterFind($results, $primary) {
//if this is a primary, structure like a secondary so entire site is same format
if ($primary) {
$class = get_class($this);
//simple fix for primary
foreach ($results as $key => $result) {
$result = $this->formatData($result, $class);
$results[$key] = $result;
}
}
return $results;
}
function formatData($result, $class) {
$array = array();
if (isset($result[$class])) {
$array = $result[$class];
unset($result[$class]);
}
$array += $result;
return $array;
}
You can also use contain in this case along with find as UserGroup.User for your desired result

Categories