dude
dude

Reputation: 71

How get value from array

I have an array like

Array
(
    [0] => stdClass Object
        (
            [id] => 1
            [org_name] => name
            [field_name] => fullname
            [new_name] => Name
            [index] => 3
            [modified] => 2016-05-17 10:45:17
        )

    [1] => stdClass Object
        (
            [id] => 3
            [org_name] => reception_no
            [field_name] => reception_no
            [new_name] => Reception No.
            [index] => 1
            [modified] => 2016-05-17 10:45:17
        )

    [2] => stdClass Object
        (
            [id] => 4
            [org_name] => pno
            [field_name] => pno
            [new_name] => Personel No.
            [index] => 0
            [modified] => 2016-05-17 10:45:17
        )

and i want for example where object has 'pno' get value of 'index' in this example for example '0' is there possible to do that ?

Upvotes: 1

Views: 63

Answers (6)

aseem
aseem

Reputation: 13

yes it is possible try this

var_dump($arr[0]->index);

OR

print_r($arr->index['0']);

Upvotes: 1

Murad Hasan
Murad Hasan

Reputation: 9583

As i am asking you about the pno, I think it was the first index like 0,1,2..., But after some conversation this is clear that it is inside the sub array.

So you need a loop here and check for the pno, if matched then echo the index. Let your array is $array

foreach ($array as $key => $val){
    if($val->org_name == 'pno'){
        echo $index = $val->index;
        break;
    }
}

Upvotes: 1

KikiTheOne
KikiTheOne

Reputation: 523

Tested with ur Array

$array = array(
        array('id'=>1,'org_name'=>'name','field_name'=>'fullname','new_name'=>'Name','index'=>3,'modified'=>'2016-05-17 10:45:17'),
        array('id'=>3,'org_name'=>'reception_no','field_name'=>'reception_no','new_name'=>'Reception No.','index'=>1,'modified'=>'2016-05-17 10:45:17'),
        array('id'=>4,'org_name'=>'pno','field_name'=>'pno','new_name'=>'Personel No.','index'=>0,'modified'=>'2016-05-17 10:45:17')
        );

This Code should do what u want

$index = '';    
foreach($array as $key => $value)
{
    if($value['org_name']=='pno')
    {
        $index = $value['index'];
    }
}
print $index;

Script only Loops through ur Array and sets $index on the last found pno index value

U can check $index in an IF, if ist empty.

Upvotes: 0

Erfan pj
Erfan pj

Reputation: 381

foreach ($arr as $items)
{
   if ($items->org_name=='pno')
     $index=$items->index;
 }

Upvotes: 2

geekasso
geekasso

Reputation: 406

Use array_search since you may not know the index

array_search

Upvotes: 0

ScaisEdge
ScaisEdge

Reputation: 133360

You can use array_search

$key1 = array_search('pno', array_column($your_array, 'field_name'));


$key2 = array_search('pno', array_column($your_array, 'org_name'));

Upvotes: 0

Related Questions