4

I have an array like this:-

$str = array(
    array(
        'amount' => 1.87,
        'user' => 'hello',
    ),
    array(
        'amount' => 0.9,
        'user' => 'test' ,
    ),
    array(
        'amount' => 9,
        'user' => 'hello',
    ),
    array(
        'amount' => 1.4,
        'user' => 'test1',
    )
);

Now I want to show the both the amounts in an html table which user 'hello' has. I tried the following for searching it :-

$ac = array_search("hello", $str);
echo $str["$ac"];

But it doesnt work. Is there anyway to show an result like this for user 'hello' :-

1.87
9

So that I can later show in html table.

4 Answers 4

2

You can use array_column()

$users = array_column($str,'user'); // get all the user list from array
$search = "hello"; // user you want to search
foreach($users as $key=>$value){ // iterate over user array
  if($value == $search){ // compare user name with search value
    echo $str[$key]['amount'] .PHP_EOL; // if matched print the corresponding amount
  }
}

https://eval.in/1052935

Sign up to request clarification or add additional context in comments.

4 Comments

Thnx it worked :D but any ideas how to get this on html table?
you can use same code in HTML TABLE. make sure file extension will be .php and add tr and td correspondingly.
<html> <head> <title>Test</title> </head> <body> <table style="width:100%"> <tr> <th>Amount</th> </tr> <tr> <td><?php $users = array_column($str,'user'); // get all the user list from array $search = "man"; // user you want to search foreach($users as $key=>$value){ // iterate over user array if($value == $search){ // compare user name with search value echo $str[$key]['amount'] ; // if matched print the corresponding amount } } ?></td> </table> </body> </html> I tried this but doesnt show properly
@JeffB please ask a new question with code and HTML. and you will get answer by some-one
2
foreach($str as $new_str){
    if($new_str['user']=="hello"){
        echo $new_str['amount'];
        echo "<br />";
    }
}

Comments

0

Here you can get this

$ac = array_column($record, ‘Hello’);
Print($ac);

Comments

0
<?php
$str = array(
 array(
'amount' => 1.87,
'user' => 'hello',
 ),
 array(
 'amount' => 0.9,
 'user' => 'test' ,
 ),
 array(
'amount' => 9,
'user' => 'hello',
 ),
 array(
 'amount' => 1.4,
 'user' => 'test1',
)
    );

$key = array_keys(array_column($str, 'user'), 'hello');
foreach($key as $value){
  echo $str[$value]["amount"]."<br/>";
}
?>

2 Comments

Thanks for spending you'r time but it shows [0,2] which is wrong.
I used to get the array index of all that containing key user="hello". I have updated just check it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.