PHP Accessing Array Value [duplicate] - php

This question already has answers here:
How can I access an array/object?
(6 answers)
Closed 6 years ago.
i am trying to access the value of an array that i have created, but it seems to fail.
I am looping through an array that sends VIA http, and adding the docno and entryno to new array called $ArrID, it can be added to the new array, however when i try to access the ArrID it seem to get nothing from the array itself while i am confident that ArrID contain the items
CODE
$ArrID = [];
foreach ($form_data_body as $key => $value) {
$docno = $value -> doc_no;
$entryno = $value -> entryno;
if($mysqli->query($sql) == 1){
$itemArr = array('docno' => $docno, 'entryno' => $entryno);
$ArrID[] = $itemArr;
}
}
if(count($ArrID)>0){
foreach ($ArrID as $key => $values) {
echo $values -> docno;
}
}

You are mixing with object and array
see http://php.net/manual/en/language.types.array.php
http://php.net/manual/en/language.types.object.php
$ArrID = [];
foreach ($form_data_body as $key => $value) {
$docno = $value['doc_no'];
$entryno = $value['entryno'];
if($mysqli->query($sql) == 1){
$itemArr = array('docno' => $docno, 'entryno' => $entryno);
$ArrID[] = $itemArr;
}
}
if(count($ArrID)>0){
foreach ($ArrID as $key => $values) {
echo $values['docno'];
}
}

How are you sure that your array has the data? Make sure by echoing the size of the array and see if its greater then zero.
Try the code below and check if it works or not. There was a redundant assign and reassign code, actually you were assigning array to a variable, and variable to an array again.
$ArrID = [];
foreach ($form_data_body as $key => $value) {
$docno = $value -> doc_no;
$entryno = $value -> entryno;
if($mysqli->query($sql) == 1) {
$ArrID[] = array('docno' => $docno, 'entryno' => $entryno);
}
}
if(count($ArrID)>0) {
foreach ($ArrID as $key => $values) {
echo $values -> docno;
}
}

Related

PHP - How to dynamically input multi-dimensional arrays only knowing the keys?

I have a multi-dimensional array with key value pairs. Some of the values of the keys are arrays, and some of the values in that array are arrays as well. It is only 3 branches deep (for now), but I am trying to recursively loop through the array, save the key for each level of the branch, and create a new array when it reaches a string that also mimics the structure of the original array. When it reaches a string, there should be a new object instantiation for each value.
The code below sort of does this, but only creates a flat array.
foreach ($data as $key => $value) {
if (!is_array($value)) {
$a_objects[$key] = new Component([$key], $value);
} else {
foreach ($value as $valueKey => $valueValue) {
if (!is_array($valueValue)) {
$a_objects[$key . "_" . $valueKey] = new Component([$key, $valueKey], $valueValue);
} else {
foreach ($valueValue as $k => $v) {
$a_objects[$key . "_" . $valueKey . "_" . $k] = new Component([$key, $valueKey, $k], $v);
}
}
}
}
Here is my own best attempt at this but it does not seem to save into the b_objects after some testing it does not seem to be saving the object instances.
$b_objects = [];
function create_r($data, $id)
{
foreach ($data as $key => $value) {
if (is_array($value) == true) {
array_push($id, $key);
create_r($value, $id);
} else {
array_push($id, $key);
$b_objects[$key] = new Component($id, $value);
$id = [];
}
}
}
$id = [];
create_r($data, $id);
echo "this is b_objects";
echo "<pre>";
print_r($b_objects);
echo "</pre>";
I verified that $id array contains the right "keys". I feel like this solution is pretty close but I have no idea how to use my $id array to mimic the structure of the $data.
I want to be able to say $b_objects[$level1key][$level2key][$level3key]...[$leveln-1key] = new Component...
Thanks!
I suggest you pass $b_objects by reference to your create_r() function. Otherwise each function call will instantiate a new $b_objects variable which is not used anywhere in the code afterwards.
Passing by reference allows the function to actually change the input array. Notice the & sign in the function declaration.
function create_r($data, $id, &$res)
{
foreach ($data as $key => $value) {
if (is_array($value) == true) {
array_push($id, $key);
create_r($value, $id, $res);
} else {
array_push($id, $key);
$res[$key] = new Component($id, $value);
$id = [];
}
}
}
$id = [];
$b_objects = [];
create_r($data, $id, $b_objects);

Error while using Error of error in PHP

I want to do the same actions thru some variables. So I created the variables of variables. But it is throwing me error - "Invalid argument supplied for foreach()" when I am looping thru $$a. I have check the type of the variable. It is array. Then what is the error ?
$edu_data = Json::decode($model->education);
$exp_data = Json::decode($model->experience);
$avail_data = Json::decode($model->availability);
$docs_data = Json::decode($model->documents);
$model_edu = new \admin\models\ApplicantEducation();
$model_exp = new \admin\models\ApplicantExperience();
$model_avail = new \admin\models\Availability();
$model_cre = new \admin\models\Credential();
$all = array('edu_data' => 'model_edu', 'exp_data' => 'model_exp', 'avail_data' => 'model_avail', 'docs_data' => 'model_cre');
foreach ($all as $a => $s)
{
$arr = $$a;
foreach ($arr as $v)
{
$$s->applicant_id = $applicant_id;
foreach ($arr[1] as $k1 => $v1)
{
$$s->$k1 = $v[$k1];
}
$$s->save();
}
}
Your array does not contain your variables (e.g. $model_edu), but only their respective names as string values ('model_edu'). Edit: My bad, I didn't notice this is intentional.
I suggest using a function:
function process_data($model, $data, $applicant_id) {
foreach ($data as $v) {
$model->applicant_id = $applicant_id;
foreach ($data[1] as $k1 => $v1)
{
$model->$k1 = $v[$k1];
}
$model->save();
}
}
process_data($model_edu, $edu_data);
process_data($model_exp, $exp_data);
process_data($model_avail, $avail_data);
process_data($model_docs, $docs_data);
Your code will be more easily comprehendable.
Apart from that, you can debug your code like this to find out exactly where and when the error happens:
foreach ($all as $a => $s)
{
$arr = $$a;
var_dump($arr);
foreach ($arr as $v)
{
$$s->applicant_id = $applicant_id;
var_dump($arr[1]);
foreach ($arr[1] as $k1 => $v1)
{
$$s->$k1 = $v[$k1];
}
$$s->save();
}
}
See if this is the expected value and proceed from there on.
Find out if the reason is an unexpected value in one of your variables or if it is an error in the code logic.

PHP - Find Specific Value in Array (multidimensional)

I have the an array, in which I store one value from the database like this:
$stmt = $dbh->prepare("SELECT token FROM advertisement_clicks WHERE (username=:username OR ip=:ipcheck)");
$stmt->bindParam(":username",$userdata["username"]);
$stmt->bindParam(":ipcheck",$ipcheck);
$stmt->execute();
$data = array();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
So, that gives me: array("token","token");
When I print it:
Array ( [0] => Array ( [token] => 677E2114AA26BA4351A686917652C7E1BA67A32D ) [1] => Array ( [token] => C42190F3D72C5BB6BB6B68488D1D4662A8D2A138 ) )
I then have a loop, that loops all the tokens. In that loop, I try to search for a specific token, and if it that token matches, it will be marked as "seen":
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['token'] === $id) {
return $key;
}
}
}
This is my loop:
$icon = "not-seen";
foreach($d as $value){
$token = $value["token"];
$searchParam = searchForId($token, $data);
if($searchParam == $token){
$icon = "seen";
}
}
However, searchForid() simply returns 0
What am I doing wrong?
Ok, here you can see a PHP fiddle that works
$data = array();
$data[] = array('token'=>'123');
$data[] = array('token'=>'456');
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['token'] === $id) {
return true;
}
}
return false;
}
$icon = "not-seen";
foreach($data as $value){
$token = $value["token"];
$searchParam = searchForId($token, $data);
if($searchParam){
$icon = "seen";
}
}
echo $icon;
It echos 'seen' which is expected since I compare the same array values, now assuming that your $d variable has different tokens, it should still work this way.
That means that your $d array does not contain what you claim it contains, could you print_r this variable and post it in your answer?

push array into current key

foreach ($twt_f as $t => $value) {
foreach ($posts as $p) {
if ($t == $p['user']['screen_name']) {
//
}
}
}
$twt_f looks something like this:
[teamcanada] => 467865
[radiocanadainfo] => 420248
[el_mayer] => 169241
[nowtoronto] => 148360
[torontocomms] => 121720
[jimharris] => 113786
[globalnational] => 112365
[cdnpress] => 112038
[alexanderkenton] => 106188
i want to push $p into the current key of twt_f. how should i go about this?
Pushing a value to an array:
$array["keyname"] = "Value";
Can also be done with 2 keys
$array["key1"][key2] = "Value";
Pushing a new value can also be done like this:
array_push($array,$value);
I hope this is what you searched for and answers you're question. Here is documentation of array's
$newArray = array();
foreach ($twt_f as $t => $value) {
foreach ($posts as $p) {
if ($t == $p['user']['screen_name']) {
$newArray[$t] = $p;
}
}
}

php array keys problem

I have the following code:
$rt1 = array
(
'some_value1' => 'xyz1',
'some_value2' => 'xyz2',
'value_1#30'=>array('0'=>1),
'value_2#30'=>array('0'=>2),
'value_3#30'=>array('0'=>3),
'value_1#31'=>array('0'=>4),
'value_2#31'=>array('0'=>5),
'value_3#31'=>array('0'=>6),
'some_value3' => 'xyz3',
'some_value4' => 'xyz4',
);
$array_30 = array
(
'0'=>1,
1=>'2',
2=>'3'
);
$array_31 = array
(
'0'=>4,
'1'=>'5',
'2'=>'6'
);
I need to make it an array and insert the array_30 and array_31 into a DB.
foreach($rt1 as $value){
$rt2[] = $value['0'];
}
The question was updated, so here is an updated answer. Quick check, you should really try and update this to whatever more generic purpose you have, but as a proof of concept, a runnable example:
<?php
$rt1 = array
(
'some_value1' => 'xyz1',
'some_value2' => 'xyz2',
'value_1#30'=>array('0'=>1),
'value_2#30'=>array('0'=>2),
'value_3#30'=>array('0'=>3),
'value_1#31'=>array('0'=>4),
'value_2#31'=>array('0'=>5),
'value_3#31'=>array('0'=>6),
'some_value3' => 'xyz3',
'some_value4' => 'xyz4',
);
$finalArrays = array();
foreach($rt1 as $key=>$value){
if(is_array($value)){
$array_name = "array_".substr($key,-2);
${$array_name}[] = $value['0'];
}
}
var_dump($array_30);
var_dump($array_31);
?>
will output the two arrays with the numbers 1,2,3 and 4,5,6 respectivily
i assume you want to join the values of each of the second-level arrays, in which case:
$result = array();
foreach ($rt1 as $arr) {
foreach ($arr as $item) {
$result[] = $item;
}
}
Inspired by Nanne (which reminded me of dynamically naming variables), this solution will work with every identifier after the \#, regardless of its length:
foreach ( $rt1 as $key => $value )
{
if ( false == strpos($key, '#') ) // skip keys without #
{
continue;
}
// the part after the # is our identity
list(,$identity) = explode('#', $key);
${'array_'.$identity}[] = $rt1[$key]['0'];
}
Presuming that this is your actual code, probably you will need to copy the array somewhere using foreach and afterwards create the new array as you wish:
foreach($arr as $key => $value) {
$arr[$key] = 1;
}

Categories