how to get the value of an object inside an array? - php

I have this array of objects:
$table=[{"count":"2","id_f":"2255"},{"count":"6","id_f":"5886"}];
I want to get the value of id_f of each object and check if this value exist in another array ,I tried with this but it gives me the wrong result:
foreach($table as $t){
if (in_array($t[$id_f],$array){
//dosomething}
}else{
//do something else
}
}
I also tried with this:
foreach($table as $t){
if (in_array($t->$id_f,$array){
//dosomething}
}else{
//do something else
}
}
I can't get the right result , I will appreciate any help.

Another approach without foreach loop:
<?php
$table=json_decode('[{"count":"2","id_f":"2255"},{"count":"6","id_f":"5886"}]');
$data = [10, 20, 2255];
array_walk($table, function($obj) use (&$data) {
if (in_array($obj->id_f, $data)) {
echo "+";
} else {
echo "-";
}
});
The output obviously is:
+-

You dont show a json_decode() anywhere in your code, thats the first thing to do with a JSON String, to decode it into a PHP data structure. In this case an array of objects.
$other_array = array('2255', '9999');
$table='[{"count":"2","id_f":"2255"},{"count":"6","id_f":"5886"}]';
$array = json_decode($table);
foreach ( $array as $obj ) {
if (in_array($obj->id_f, $other_array)) {
echo 'Found one ' . $obj->id_f . PHP_EOL;
} else {
echo 'No match for ' . $obj->id_f . PHP_EOL;
}
}
Results
Found one 2255
No match for 5886

There's no need for the dollar sign before your Object property name (actually, it won't work, except of course if $id_f is a real variable which has for value 'id_f', but somehow I doubt it) :
foreach ($table as $t) {
if (in_array($t->id_f, $array){
// do something
} else {
// do something else
}
}

it can be done like this:
to define the object array you can define like below with json string approach. or to define object is like this $table = new stdClass();
<?php
$table='[{"count":"2","id_f":"2255"},{"count":"6","id_f":"5886"}]';
$obj = json_decode($table);
$array=array("2555","2255");
foreach($obj as $t){
if (in_array($t->id_f,$array)){
//dosomething
}else{
//do something else
}
}
?>

Related

PHP If statements and Arrays

I have an array
$results = array(101, 102, 103, 104, 105)
I also have a input field where the user enters a number
<input type ="text" name="invoice" />
I put what the number that user enters in, into a variable
$id = $_POST['invoice']
How would I write an if statement to check to see if the number that user entered is in that array
I have tried doing in a for each loop
foreach($result as $value){
if($value == $id){
echo 'this';
}else{
continue;
}
is there a better way of doing this?
if (in_array($id, $results)) {
// ...
}
http://php.net/manual/en/function.in-array.php
Use in_array():
if (in_array($_POST['invoice'], $your_array)) {
... it's present
}
ok you can try this:
if ( in_array($id, $results))
{
// execute success
}
else
{
// execute fail
}
You can use in_array, like the others have suggested
if(in_array($id,$results)) {
//do something
} else {
$no_invoice = true;
}
but if you happen to want to use your array key for anything, you can kill two birds with one stone.
if($key = array_search($id,$results,true)) {
echo 'You chose ' . $results[$key] . '<br />';
}
Obviously for echoing you don't need my method - you could just echo $id - but it's useful for other stuff. Like maybe if you had a multi-dimensional array and element [0]'s elements matched up with element[1]'s elements.
If you are looking to compare values of one array with values of another array in sequence then my code is really simple: check this out it will work like this:
if (1st value of array-1 is equal to 1st value of array-2) { $res=$res+5}
if($_POST){
$res=0;
$r=$_POST['Radio1']; //array-1
$anr=$_POST['answer']; //array-2
$arr=count($r);
for($ac=0; $ac<$arr; $ac++){
if($r[$ac]==$anr[$ac]){
$res=$res+5;
}
}
echo $res;
}
Not quite.
your way is good enough, it only needs to be corrected.
foreach($results as $value){
if($value == $id){
echo 'this';
break;
}
}
is what you really wanted

convert array to object in php

In php I am converting posted data from a form to objects like this:
<?php
...some code...
$post = new stdClass;
foreach ($_POST as $key => $val)
$post->$key = trim(strip_tags($_POST[$key]));
?>
Then in my page I just echo posted data like this :
<?php echo $post->Name; ?>
<?php echo $post->Address; ?>
etc...
This works fine but I have multiple checkboxes that are part of a group and I echo the results of that, like this:
<?php
$colors = $_POST['color_type'];
if(empty($colors))
{
echo("No color Type Selected.");
}
else
{
$N = count($colors);
for($i=0; $i < $N; $i++)
{
echo($colors[$i] . ", ");
}
}
?>
That works when I am just using array, but how do I write this as object syntax?
using your code
function array_to_object($arr) {
$post = new stdClass;
foreach ($arr as $key => $val) {
if(is_array($val)) {
$post->$key = post_object($val);
}else{
$post->$key = trim(strip_tags($arr[$key]));
}
}
return $post;
}
$post = array_to_object($_POST);
or more complex solution
function arrayToObject($array) {
if(!is_array($array)) {
return $array;
}
$object = new stdClass();
if (is_array($array) && count($array) > 0) {
foreach ($array as $name=>$value) {
$name = strtolower(trim($name));
if (!empty($name)) {
$object->$name = arrayToObject($value);
}
}
return $object;
}
else {
return FALSE;
}
}
from http://www.richardcastera.com/blog/php-convert-array-to-object-with-stdclass
why would you want that? What's wrong with an array?
Use Object Oriented Programming, which might be what you are looking for. Treat it as an object, by making a class called Color and doing $colors[$i] = new Color();
This way you can do whatever you want with it, and add functions to it.
Pretty simple -- when you attach the color_type key to your object, it'll become an array that's a property of your object. This is most likely what you want: you probably won't want to turn that array into its own stdClass-based object, because then you won't be able to iterate through all the values (as easily). Here's a snippet:
<?php
// putting in both of these checks prevents you from throwing an E_WARNING
// for a non-existent property. E_WARNINGs aren't dangerous, but it makes
// your error messages cleaner when you don't have to wade through a bunch
// of E_WARNINGS.
if (!isset($post->color_type) || empty($post->color_type)) {
echo 'No colour type selected.'; // apologies for the Canadian spelling!
} else {
// this loop does exactly the same thing as your loop, but it makes it a
// bit more succinct -- you don't have to store the count of array values
// in $N. Bit of syntax that speeds things up!
foreach ($post->color_type as $thisColor) {
echo $thisColor;
}
}
?>
Hope this helps! Of course, in a real-life setting, you'll want to do all sorts of data validation and cleaning -- for instance, you'll want to check that the browser actually passed an array of values for $_POST['color_type'], and you'll want to clean the output in case someone is trying to inject an exploit into your page (by going echo htmlspecialchars($thisColor); -- this turns all characters like < and > into HTML entities so they can't insert JavaScript code).

PHP Array foreach question

I have a question about arrays and foreach.
If i have an array like this:
$test_arr = array();
$test_arr['name1'] = "an example sentence";
$test_arr['anything'] = "dsfasfasgsdfg";
$test_arr['code'] = "4334refwewe";
$test_arr['empty1'] = "";
$test_arr['3242'] = "";
how can I do a foreach and "pick" only the ones that have values? (in my array example, would only take the first 3 ones, name1, anything and code).
I tried with
foreach ($test_arr as $test) {
if (strlen($test >= 1)) {
echo $test . "<br>";
}
}
but it doesn't work. Without the "if" condition it works, but empty array values are taken into consideration and I don't want that (because I need to do a <br> after each value and I don't want a <br> if there is no value)
Sorry if I don't explain myself very well, I hope you understand my point. Shouldn't be too difficult I guess..
Thanks for your help !
Maybe will work
foreach ($test_arr as $test) {
if (strlen($test)!=="") {
echo $test . "<br>";
}
}
Your solution with corrected syntax:
foreach ($test_arr as $test) {
if (strlen($test)>=1) {
echo $test . "<br>";
}
}
Since empty strings are false, you could just do this (but you'd exclude 0's with the if):
foreach ($test_arr as $key => $val) {
if ($val) {
echo $val. "<br>";
}
}
If it has to be an empty string then (excluding 0 and FALSE):
foreach ($test_arr as $key => $val) {
// the extra = means that this will only return true for strings.
if ($val !== '' ) {
echo $val. "<br>";
}
}
Since it looks like you're using an associative array, you should be able to do this:
foreach( $test_arr as $key => $value )
{
if( $value != "" )
{
echo $value . "<br />";
}
}
As shown, you can test $value for an empty string directly. Since this is precisely the test you are trying to accomplish, I would hope that this would solve your problem perfectly.
On another note, this is pretty straight forward and should be very maintainable in the future when you've forgotten exactly what it was that you were doing!
You are better off to use a while loop like this:
while(list($test_key, $test_value) = each($test_arr))
{
if($test_value != "") { echo $test_value . "<br/>"; }
}
reset($test_arr);
If your array gets large, the while will be much faster. Even on small arrays, I have noticed a big difference in the execution time.
And if you really don't want the array key. You can just do this:
while(list(, $test_value) = each($test_arr))
{
if($test_value != "") { echo $test_value . "<br/>"; }
}
reset($test_arr);
You can check if the value is emtpy with empty().
Note that values like 0 or false are considered empty as well, so you might have to check for string length instead.
just a simple typing error:
foreach ($test_arr as $test) {
if (strlen($test) >= 1) {
echo $test . "<br>";
}
}
Try this:
foreach ($test_arr as $test) {
if (strlen($test) > 0) {
echo $test . "<br>";
}
}

Replace value in array doesn't work

I'm going crazy, spent a couple of hours trying different methods in replace values in arrays, but I can't get it to work.
foreach($potentialMatches as $potentialKey)
{
$searchKeywordQuery = "SELECT keyword, id FROM picture WHERE id='$potentialKey'";
$searchKeywords = mysql_query($searchKeywordQuery) or die(mysql_error());
while ($searchKeyWordsRow = mysql_fetch_array($searchKeywords))
{
$keyword = $searchKeyWordsRow['keyword'];
$pictureKeywordArray[$searchKeyWordsRow['id']]['keywords'] = explode(",", $keyword);
$pictureKeywordArray[$searchKeyWordsRow['id']]['match'] = 4;
}
}
foreach($pictureKeywordArray as $key = > $picValue)
{
foreach($picValue['keywords'] as $key = > $picIdValue)
{
if ($picIdValue == $searchIdKey)
{
echo $picValue['match'];
$picValue['match']++;
echo $picValue['match'];
}
}
}
foreach($pictureKeywordArray as $key = > $picValue)
{
echo $picValue['match'];
}
I'm novice as you can see, When I echo the picValue['match'] in the foreach loop it gives me a correct value after "++". But then below when I call the array again it gives me the value of 4 instead of 5 as intended. Thanks in advance for any help with this.
Cause you work with the item copy in first case try $pictureKeywordArray[$key]['match'] instead of $picValue['match']
In that second foreach you need to call it by reference:
foreach($pictureKeywordArray as $key => &$picValue)
{ //^-- `&` makes it by reference
foreach($picValue['keywords'] as $key => $picIdValue)
{
if ($picIdValue == $searchIdKey)
{
echo $picValue['match'];
$picValue['match']++; //now updates what you want it to update
echo $picValue['match'];
}
}
}
foreach works on a copy of the data. You must use a reference to modify the original:
foreach ($foo as $i => &$f)
{
$f++;
}
unset($f); // important to do this if you ever want to reuse that variable later

print an array as code

I want to convert a big yaml file to PHP array source code. I can read in the yaml code and get back a PHP array, but with var_dump($array) I get pseudo code as output. I would like to print the array as valid php code, so I can copy paste it in my project and ditch the yaml.
You're looking for var_export.
You could use var_export, serialize (with unserialize on the reserving end), or even json_encode (and use json_decode on the receiving end). The last one has the advantage of producing output that can be processed by anything that can handle JSON.
Don't know why but I could not find satisfying code anywhere.
Quickly wrote this. Let me know if you find any errors.
function printCode($array, $path=false, $top=true) {
$data = "";
$delimiter = "~~|~~";
$p = null;
if(is_array($array)){
foreach($array as $key => $a){
if(!is_array($a) || empty($a)){
if(is_array($a)){
$data .= $path."['{$key}'] = array();".$delimiter;
} else {
$data .= $path."['{$key}'] = \"".htmlentities(addslashes($a))."\";".$delimiter;
}
} else {
$data .= printCode($a, $path."['{$key}']", false);
}
}
}
if($top){
$return = "";
foreach(explode($delimiter, $data) as $value){
if(!empty($value)){
$return .= '$array'.$value."<br>";
}
};
return $return;
}
return $data;
}
//REQUEST
$x = array('key'=>'value', 'key2'=>array('key3'=>'value2', 'key4'=>'value3', 'key5'=>array()));
echo printCode($x);
//OUTPUT
$array['key'] = 'value';
$array['key2']['key3'] = 'value2';
$array['key2']['key4'] = 'value3';
$array['key2']['key5'] = array();
Hope this helps someone.
An other way to display array as code with indentation.
Tested only with an array who contain string, integer and array.
function bo_print_nice_array($array){
echo '$array=';
bo_print_nice_array_content($array, 1);
echo ';';
}
function bo_print_nice_array_content($array, $deep=1){
$indent = '';
$indent_close = '';
echo "[";
for($i=0; $i<$deep; $i++){
$indent.=' ';
}
for($i=1; $i<$deep; $i++){
$indent_close.=' ';
}
foreach($array as $key=>$value){
echo "<br>".$indent;
echo '"'.$key.'" => ';
if(is_string($value)){
echo '"'.$value.'"';
}elseif(is_array($value)){
bo_print_nice_array_content($value, ($deep+1));
}else{
echo $value;
}
echo ',';
}
echo '<br>'.$indent_close.']';
}

Categories