selecting value of particular index with PHP foreach - php

I have the following loop that creates an array
while($row1 = mysqli_fetch_assoc($result1))
{
$aliens[] = array(
'username'=> $row1['username'],
'personal_id'=> $row1['personal_id']
);
}
It produces the following result
Array (
[0] =>
Array ( [username] => nimmy [personal_id] => 21564865 )
[1] =>
Array ( [username] => aiswarya [personal_id] => 21564866 )
[2] =>
Array ( [username] => anna [personal_id] => 21564867 )
Then I have another loop as follows, inside which, I need to fetch the personal_id from the above array. I fetch it as follows.
foreach($aliens as $x=>$x_value)
{
echo $aliens['personal_id'];
//some big operations using the
$aliens['personal_id']; variable
}
However, I can't get the values if personal_ids. I get it as null. What seems to be the problem? How can I solve it?

You have an array of "aliens", each alien is an array with personal_id and username keys.
foreach ($aliens as $index => $alien) {
echo $alien['personal_id'], PHP_EOL;
}
The foreach loop iterates its items (aliens). The $alien variable represents the current iteration's item, i.e. the alien array.

foreach($aliens as $x=>$x_value)
{
echo $x_value['personal_id'];
//some big operations using the
$x_value['personal_id']; variable
}

Related

Push a field to the end of every subArray of a multidimensional associative array

I have a PHP Multidimensional associative array structured in this way:
Array
(
[0] => Array
(
[serverid] => 1
[ip] => localhost
[name] => Server1
)
[1] => Array
(
[serverid] => 2
[ip] => localhost
[name] => Server2
)
[2] => Array
(
[serverid] => 3
[ip] => localhost
[name] => Server3
)
Now I need to push at the end of every subArray this new field with this value:
['page_url'] = base_url('/server/id/') . $server['serverid'];
Where $server['serverid'] is the serverid field relative to every single subArray.
I've tried with this cycle but seems it doesn't work:
$result = $query->result_array();
foreach($result as $server) {
$server['page_url'] = base_url('/server/id/') . $server['id'];
}
Any suggestion would be really appreciated.
If you want to modify the subarray when iterating trough an array in a foreach, you have to pass the variable as a reference using &.
If you change your code to the one below, it should work as you'll be changing the original array item instead of a created copy.
foreach($result as &$server) {
$server['page_url'] = base_url('/server/id/') . $server['id'];
}
This creates a temporary copy of the subarray, which you're changing and then throwing away on the next iteration:
foreach ($result as $server) {
$server['page_url'] = base_url('/server/id/') . $server['id'];
}
You want to change the original array. Something like this:
foreach (array_keys($result) as $index) {
$result[$index]['page_url'] = base_url('/server/id/') . $result[$index]['id'];
}
If you know you haven't mucked with the indexes in $result you could also just do:
for ($index = 0; $index < count($result); $index++) {

get the value from the associtive array in table

Array
(
[0] => Array
(
[datas] => Array
(
[res] => 1
[rows] => Array
(
[0] => stdClass Object
(
[a] => 11
[b] => 901
[c] => 2
[d] => 2
[e] => A
[f] => BT
[g] => arushi
[h] => arushi#gmail.com
[i] => 123445
[j] => 12355.jpg
)
)
)
)
[1] => Array
(
[datas] => Array
(
[res] => 1
[rows] => stdClass Object
(
[person_name] => arushi
)
)
)
)
if i get the value in that kind off array how can i get the value of
both partially with different variable m not able to understand the
structure of the array..
need to get the value in table seperatly in different different table with same page how i can get the values
You would need to do a foreach loop. The only problem is that if you want to make it dynamic and grab the data by itself without you telling it what to get. If not it means you would have to know exactly what you need and the structure of your results. But seeing that there is a pattern you can do some checks until you reach rows. For example ($array would be the variable that has the data you provided):
foreach ($array AS $arr) {
// To make you function/check work faster,
// before even entering to fetch for data
// you can check if it has any data, else you
// probably will end up with an error
if (isset ($arr ['datas']) && $arr ['datas']) {
foreach ($arr ['datas'] AS $data) {
if (isset ($arr ['res']) && 0 < $arr ['res']) {
// here is where it gets tricky because
// from you example its either an array or an object
// but the kool part about it is that you can convert an object into an array
// or just leave it as is because the foreach will take care of it either way :)
// first check it it is an object and convert if yes
$row = $arr ['rows'];
if (!is_array ($row))
$row = (array)$row; // converting it to array is super easy :)
foreach ($row AS $key=>$dat) {
// from here your result can either be another array or just data
// so you run the check once more
if (is_array ($dat)) {
foreach ($dat AS $k=>$d) {
echo "data for $k is $d";
}
}
else
echo "data for $key is $dat";
}
}
}
}
}
You can use foreach to loop through the arrays which have keys starting from 0 to n. So that you can foreach through the main array to get the datas array for all the keys. For getting rows childs you can use another foreach inside it to get each items. But for rows it is object , so you have to use -> to select the key. see below example code. But on your array the second array consist different formate in rows array. so make it like a common formate to loop through it easily.
For eg :-
foeach($parent_array as $array){
$data=$array['datas'];
$res = $data['res'];
$rows=$data['rows'];
foreach($rows as $row){
echo $row->a; // to get the value of key a = 11
}
}

How to output different levels of an array

As a newbie, does anyone have any good tutorials to help me understand different levels of an array? What I'm trying to learn is how to echo different levels, e.g. here is the output array:
Array
(
[meta] =>
Array
(
[total_record_count] => 1
[total_pages] => 1
[current_page] => 1
[per_page] => 1
)
[companies] =>
Array
(
[0] =>
Array
(
[id] => 291869
[url] => https://api.mattermark.com/companies/291869
[company_name] => gohenry.co.uk
[domain] => gohenry.co.uk
)
)
[total_companies] => 1
[page] => 1
[per_page] => 1
)
And here is the code to parse the array:
foreach($jsonObj as $item)
{
echo $item['total_companies'];
}
I'm really struggling to find the structure and how to output each items, e.g. tried things like:
echo $item[0]['total_companies'];
echo $item['companies'][0]['id'];
Any help or pointers would be greatly received.
Well, Lets start, You have a multi-dimensional array. For a multi-dimensional array you need to use looping e.g: for, while, foreach. For your purpose it is foreach.
Start with the array dimension, Array can be multi-dimension, Like you have multi-dimension. If you have an array like below, then it is single dimension.
array(
key => value,
key2 => value2,
key3 => value3,
...
)
Now, How can you know what is a multi-dimension array, If you array has another array as child then it is called multi-dimensional array, like below.
$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dimensional" => array(
"array" => "foo"
)
)
);
Its time to work with your array. Suppose you want to access the value of company_name, what should you do?? Let your array name is $arr.
First you need to use a foreach loop like:
foreach($arr as $key => $val)
The keys are (meta, companies, total_companies...), they are in the first dimension. Now check if the key is company_name or not, if it matches than you got it. Or else you need to make another loop if the $val is an array, You can check it using is_array.
By the same processing at the last element your loop executes and find your value.
Learning
Always a good idea to start with the docs:
arrays: http://php.net/manual/en/language.types.array.php
foreach: http://php.net/manual/en/control-structures.foreach.php
As for tutorials, try the interactive tutorial over at codecademy: https://www.codecademy.com/learn/php
Unit 4 has a tutorial on arrays
Unit 11 has a lesson on advanced arrays.
Your code
As for your code, look at the following which I will show you your array structure and how to access each element. Perhaps that will make things clearer for you.
So lets say your array is named $myArray, see how to access each part via the comments. Keep in mind this is not php code, I'm just showing you how to access the array's different elements.
$myArray = Array
(
// $myArray['meta']
[meta] => Array (
// $myArray['meta']['total_record_count']
[total_record_count] => 1
// $myArray['meta']['total_pages']
[total_pages] => 1
// $myArray['meta']['current_page']
[current_page] => 1
// $myArray['meta']['per_page']
[per_page] => 1
)
// $myArray['companies']
[companies] => Array (
// $myArray['companies'][0]
[0] => Array (
// $myArray['companies'][0]['id']
[id] => 291869
// $myArray['companies'][0]['url']
[url] => https://api.mattermark.com/companies/291869
// $myArray['companies'][0]['company_name']
[company_name] => gohenry.co.uk
// $myArray['companies'][0]['domain']
[domain] => gohenry.co.uk
)
)
// $myArray['total_companies']
[total_companies] => 1
// $myArray['page']
[page] => 1
// $myArray['per_page']
[per_page] => 1
)
As for your for each loop
foreach($jsonObj as $item)
{
echo $item['total_companies'];
}
What the foreach loop is doing is looping through each first level of the array $jsonObj, so that would include:
meta
companies
total_companies
page
per_page
Then within the curly braces {} of the foreach loop you can refer to each level by the variable $item.
So depending on what you want to achieve you need to perhaps change your code, what is it you're trying to do as it's not really clear to me.
As for the code within the loop:
echo $item['total_companies'];
It won't work because you're trying to access an array with the index of total_companies within the first level of the $jsonObj array which doesn't exist. For it to work your array would have to look like this:
$jsonObj = array (
'0' => array ( // this is what is reference to as $item
'total_companies' => 'some value'
)
)
What you want to do is this:
foreach($jsonObj as $item)
{
echo $jsonObj['total_companies'];
}
As for your final snippet of code:
echo $item[0]['total_companies'];
Answered this above. Access it like $jsonObj['total_companies'];
echo $item['companies'][0]['id'];
If you want to loop through the companies try this:
foreach($jsonObj['companies'] as $item)
{
// now item will represent each iterable element in $jsonObj['companies]
// so we could do this:
echo $item['id'];
}
I hope that all helps! If you don't understand please make a comment and I'll update my answer.
Please take a look in to here and here
Information about php arrays
Try recursive array printing using this function:
function recursive($array){
foreach($array as $key => $value){
//If $value is an array.
if(is_array($value)){
//We need to loop through it.
recursive($value);
} else{
//It is not an array, so print it out.
echo $value, '<br>';
}
}
}
if you know how deep your array structure you can perform nested foreach loop and before every loop you have to check is_array($array_variable), like :
foreach($parent as $son)
{
if(is_array($son))
{
foreach($son as $grandson)
{
if(is_array($son))
{
foreach($grandson as $grandgrandson)
{
.....
......
.......
}
else
echo $grandson;
}
else
echo $parent;
}
else
echo $son;
}
hope it will help you to understand

Through an array with other array in php

I have a question for you, I need to through an array with other arrays in php but i through only the last array, my array is:
Array
(
[0] => Array
(
[syn_id] => 17070
[syn_label] => fd+dfd
)
[1] => Array
(
[syn_id] => 17068
[syn_label] => fds+dsfds
)
[2] => Array
(
[syn_id] => 17069
[syn_label] => klk+stw
)
)
My php:
$a_ddata = json_decode(method(), true);
foreach ($a_ddata as $a_data)
{
$a_data['syn_label'] = urldecode(utf8_decode($a_data['syn_label']));
}
With this code I through only the last array [2], but how to through array?please help me
I need to get the array:
Array
(
[0] => Array
(
[syn_id] => 17070
[syn_label] => fd dfd
)
[1] => Array
(
[syn_id] => 17068
[syn_label] => fds dsfds
)
[2] => Array
(
[syn_id] => 17069
[syn_label] => klk stw
)
)
$a_ddata = json_decode(method(), true); $i=0;
foreach ($a_ddata as $a_data)
{
$a_data_f[$i]['syn_id'] = $a_data['syn_id'];
$a_data_f[$i]['syn_label'] = urldecode(utf8_decode($a_data['syn_label']));
$i++;
}
This should be your answer..
When you iterate through something using foreach, by default PHP makes a copy of each element for you to use within the loop. So in your code,
$a_ddata = json_decode(method(), true);
foreach ($a_ddata as $a_data)
{
// $a_data is a separate copy of one of the child arrays in $a_ddata
// this next line will modify the copy
$a_data['syn_label'] = urldecode(utf8_decode($a_data['syn_label']));
// but at the end of the loop the copy is discarded and replaced with a new one
}
Fortunately the manual page for foreach gives us a way to override this behavior with the reference operator &. If you place it between the as keyword and your loop variable, you're able to update the source array within your loop.
$a_ddata = json_decode(method(), true);
foreach ($a_ddata as &$a_data)
{
// $a_data is now a reference to one of the elements to $a_ddata
// so, this next line will update $a_ddata's individual records
$a_data['syn_label'] = urldecode(utf8_decode($a_data['syn_label']));
}
// and you should now have the result you want in $a_ddata
This should help:
$a_data['syn_label'][] = urldecode(utf8_decode($a_data['syn_label']));
For each iteration you are only replacing $a_data['syn_label']. By adding [] you are making it a multi dimension array which increments for every iteration.

Using the nth item in a php array

I have created an array, as follows:
$results = array();
do {
$results[] = $row_products;
} while ($row_products = mysql_fetch_assoc($products));
print_r($results);
This prints out the array like this:
Array (
[0] => Array (
[productName] => product1
)
[1] => Array (
[productName] => product2
)
[2] => Array (
[productName] => product3
)
I want to now use say the second item in the array in another mysql query.
But I cannot define it. I have tried
$results[1];
but this does not work.
So in effect, if I echo the second item, it would print 'product2'.
You should learn the basics about arrays here: http://www.php.net/manual/en/language.types.array.php
You are using a nested array, so you have the access it like this:
echo $results[1]['productName'];
Another solution would be to use $results[] = $row_products['productName']; and then just echo $results[1].
In addition, you should use a while loop instead of a do/while loop because $row_products does not seem to be defined for the first iteration.
while ($row_products = mysql_fetch_assoc($products)) {
$results[] = $row_products;
}
try this :
echo $results[1]['productName'] ;
$results[1] is an array, If you want see the array print_r($results[1]);

Categories