作者jacobcan118 (jacobcan118)
看板PHP
標題[請益] 從array,object裡找值
時間Sun Feb 23 08:50:24 2014
我想寫一個function能在從object或array裡指定的位子找指定的值.
array 的行式會像ary一樣有含多個object
請問除了下面寫法有更好的方法嗎?
<?php
class Foo
{
public $index1 = "string";
public $index2 = "valb";
public $index3 = "valc";
}
$obj_a = new Foo;
$obj_b = new Foo;
$obj_c = new Foo;
$obj_d = new Foo;
$obj = new Foo;
$ary = array($obj_a, $obj_b, $obj_c, $obj_d);
function stringchk($obj = "", $needle = "", $str = "") {
foreach ( $obj as $key => $val) {
if (gettype($val) == "string") {
if (($key == $needle) && ($val == $str))
return "y";
}
elseif (gettype($val) == "object") {
if ($val->$needle == $str)
return "y";
}
else
return "n";
}
}
$needle = "index1";
echo stringchk($obj, $needle, "string" );
?>
[A
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 71.183.242.84
1F:→ liaosankai:你的問題描述寫的不是很明確 02/23 16:42
2F:→ jacobcan118:我想要一個function能判斷在指定的位子值是否為指定 02/24 13:48
3F:→ jacobcan118:如在object index1裡是否值為string,不過這function 02/24 13:50
4F:→ jacobcan118:要能接收的input有兩種object和array,array裡得值行 02/24 13:51
5F:→ jacobcan118:所有進來Object格式一樣都是index1,index2,index3 02/24 13:52