How do I skip over first bracket in array with php? - php

I am needing to echo out the [number], but as you can see each array has a different parent [], how do I by pass the first one and get go to the [number]?
I basically need to skip over first [], and go to the second on that is [number]
Array
(
[e2a4789d22ff47779722b8d8643894cd] => Array
(
[type] => workphone
[visibility] => public
[number] => 999-999-9999
[id] => 2
[order] => 0
[preferred] => 1
)
)
Array
(
[1603ebeff250437480f5ce046cac36aa] => Array
(
[type] => workphone
[visibility] => public
[number] => 999-999-9999
[id] => 3
[order] => 0
[preferred] => 1
)
)
Array
(
[215590630122] => Array
(
[type] => workphone
[visibility] => public
[number] => 999-999-9999
[order] => 0
[preferred] =>
)
)

Your solution for this is using the foreach-loop. Which gives you then the value of the element as variable you tell PHP to assign to.
foreach($array as $element) {
}

You have to use reset function to get the first element of array.
e.g.
$firstElement = reset($arr);
echo $firstElement['number'];

You can just loop over the elements in the array(s) using foreach.
foreach($data as $ele){
foreach($ele as $id=>$val){
echo $val['number'];
}
}

Just an example
$array = $yourarray;
foreach($array as $k=>$v) {
echo $v['number'] . '<br>';
}
hope this helps...

The first bracket is just a unique key index foreach subsequent set of data. for example you can get the first set by accessing through the key like this
$data['e2a4789d22ff47779722b8d8643894cd']
// will return
Array
(
[type] => workphone
[visibility] => public
[number] => 999-999-9999
[id] => 2
[order] => 0
[preferred] => 1
)
loop through the array to access the data you want,
// declare your array if you want to save data in array
$numbers = [];
foreach($data $key =>$value){
// echo just the number
echo $value['number'];
// echo the key and number
echo $key.' '.$value;
// or you can build an array
$numbers[$key] = $value['number'];
}
print_r($numbers);
Hope you find this useful, for more info about arrays take a look at this http://php.net/manual/en/language.types.array.php

foreach ($array as $id => $element)
{
// will echo 999-999-9999
echo $element['number'];
}
$array is the whole data structure. We go through as index, that is the $id, which is for example e2a4789d22ff47779722b8d8643894cd and the $element is the element in the $array[$id] so in the $array[e2a4789d22ff47779722b8d8643894cd]
So the $element is the small array in the large array, and it contains data like:
Array
(
[type] => workphone
[visibility] => public
[number] => 999-999-9999
[id] => 2
[order] => 0
[preferred] => 1
)
So if you need the number attribute, you type $element['number'] and you get it.

If your variable was in an array called $elements then it would look like:
$elements['e2a4789d22ff47779722b8d8643894cd']['number']

Related

Taking out just one value from an array

I have an array which is
Array ( [0] => Array ( [picture] => 5a55ed8d8a5c8910913.jpeg
[id] => 1284
[price_range] => Rs 12000 - 9000
[name] => Brown Beauty Office Chair )
[1] => Array ( [picture] => 5a55eefeb9a8e255836.jpeg
[id] => 1285
[price_range] => Rs 8989 - 7000
[name] => Chang Series Office Chair (Grey)
)
)
Now I am fetching the value of id on clicking a remove button, the value I fetch is 1284.
I want to take out just [id]=> 1284 from the above array and then display it using a foreach loop. How I can delete just the [id]=> 1284 without disturbing the other id values and other element.
In the above array I would like to delete one particular id value say just the [id]=> 1284 and keep all other elements intact and as it is.
Any help is welcome.
Use array_search and array_column, to find by id and remove by unset method,
<?php
$array = [
["id"=>123,"desc"=>"test1"],
["id"=>456,"desc"=>"test2"],
["id"=>789,"desc"=>"test3"],
];
$id = 456;
$index = array_search($id, array_column($array, 'id'));
unset($array[$index]);
print_r($array);
?>
Live Demo
Array
(
[0] => Array
(
[id] => 123
[desc] => test1
)
[2] => Array
(
[id] => 789
[desc] => test3
)
)
Since you asked how to achieve it using foreach, I came up with this.
$array = Array (Array ( 'picture' => '5a55ed8d8a5c8910913.jpeg','id' => 1284,'price_range' => 'Rs 12000 - 9000', 'name' => 'Brown Beauty Office Chair'),
Array ( 'picture' => '5a55eefeb9a8e255836.jpeg','id' => 1285,'price_range' => 'Rs 8989 - 7000','name' => 'Chang Series Office Chair (Grey)')
);
foreach($array as $key => $val) {
$id = $array[$key]['id'];
if($id === 1284){
unset($array[$key]['id']);
}
}
print_r($array)
?>
You can also use this too:
<?php
$element_to_remove = 1284;
$i = 0;
foreach($array as $this_arr){
$index = array_search($element_to_remove, $this_arr);
//unset($this_arr[$index]); this formate does not remove element from array
//but below works fine
if(isset($array[$i][$index])){
unset($array[$i][$index]);
}
}
print_r($array);
?>

How get value from array

I have an array like
Array
(
[0] => stdClass Object
(
[id] => 1
[org_name] => name
[field_name] => fullname
[new_name] => Name
[index] => 3
[modified] => 2016-05-17 10:45:17
)
[1] => stdClass Object
(
[id] => 3
[org_name] => reception_no
[field_name] => reception_no
[new_name] => Reception No.
[index] => 1
[modified] => 2016-05-17 10:45:17
)
[2] => stdClass Object
(
[id] => 4
[org_name] => pno
[field_name] => pno
[new_name] => Personel No.
[index] => 0
[modified] => 2016-05-17 10:45:17
)
and i want for example
where object has 'pno' get value of 'index' in this example for example '0'
is there possible to do that ?
foreach ($arr as $items)
{
if ($items->org_name=='pno')
$index=$items->index;
}
As i am asking you about the pno, I think it was the first index like 0,1,2..., But after some conversation this is clear that it is inside the sub array.
So you need a loop here and check for the pno, if matched then echo the index. Let your array is $array
foreach ($array as $key => $val){
if($val->org_name == 'pno'){
echo $index = $val->index;
break;
}
}
yes it is possible try this
var_dump($arr[0]->index);
OR
print_r($arr->index['0']);
You can use array_search
$key1 = array_search('pno', array_column($your_array, 'field_name'));
$key2 = array_search('pno', array_column($your_array, 'org_name'));
Use array_search since you may not know the index
array_search
Tested with ur Array
$array = array(
array('id'=>1,'org_name'=>'name','field_name'=>'fullname','new_name'=>'Name','index'=>3,'modified'=>'2016-05-17 10:45:17'),
array('id'=>3,'org_name'=>'reception_no','field_name'=>'reception_no','new_name'=>'Reception No.','index'=>1,'modified'=>'2016-05-17 10:45:17'),
array('id'=>4,'org_name'=>'pno','field_name'=>'pno','new_name'=>'Personel No.','index'=>0,'modified'=>'2016-05-17 10:45:17')
);
This Code should do what u want
$index = '';
foreach($array as $key => $value)
{
if($value['org_name']=='pno')
{
$index = $value['index'];
}
}
print $index;
Script only Loops through ur Array and sets $index on the last found pno index value
U can check $index in an IF, if ist empty.

Pushing a sub array into the same array

I am trying to put content of one array into the same array. Here I have an array $mclass with values such as
Array
(
[0] => stdClass Object
(
[room_id] => 1,3,5
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
)
You can see I have room_id index with 1,3,5 value. Now, I want to explode the room_id and get duplicate of same array index data with change of room_id and push into the array. and finally delete the current array index such as [0]. Here I want the final result as.
Array
(
[0] => stdClass Object
(
[room_id] => 1
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
[1] => stdClass Object
(
[room_id] => 3
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
[2] => stdClass Object
(
[room_id] => 5
[day] => 1
[class_teacher] => TEA-2014-2
[final_exam_date] => 2015-09-21
)
)
Here is my code for the same:
if(count($mclass)>0)
{
foreach($mclass as $mclasskey=>$mclass_row)
{
/* Room ID Calculation */
if(isset($mclass[$mclasskey]))
{
$temp_room_id = explode(',',$mclass_row->room_id);
if(count($temp_room_id)>1)
{
foreach($temp_room_id as $trkey=>$tr)
{
if(!in_array($temp_room_id[$trkey], $morning_class_semester))
{
array_push($morning_class_semester,$temp_room_id[$trkey]);
}
}
if(count($morning_class_semester)>0)
{
foreach($morning_class_semester as $mcskey=>$mcs)
{
$index_count = count($new_test);
$test[$index_count] = $mclass[$mclasskey];
$test[$index_count]->room_id = $morning_class_semester[$mcskey];
array_push($new_test,$test[$index_count]);
}
unset($mclass[$mclasskey]);
}
}
}
}
}
The code below does what you're looking for using only arrays. So you'll have to change the array access operators to -> since you're accessing an object. I'd do so, but it would break the example, so I'll leave that up to you.
Code Explained:
Loop through array selecting each subarray (object in your case), explode on the $item('room_id') ... ($item->room_id in your case) ... and create sub arrays, via loop, from that using the data from the original using each key. Remove the original item (which has the combined room_ids) and combine the placeholder and original array.
<?php
//Establish some data to work with
$array = array(
array(
"room_id" => "1,3,5",
"day" => 1,
"class_teacher" => "TEA-2014-2",
"final_exam_date" => "2015-09-21",
));
foreach ($array as $key => $item) {
$placeholder = array();
$ids = explode(',',$item['room_id']);
if (count($ids) > 1) {
foreach ($ids as $id) {
$push = array(
'room_id' => $id,
'day' => $item['day'],
'class_teacher' => $item['class_teacher'],
'final_exam_date' => $item['final_exam_date']
);
array_push($placeholder, $push);
}
$array = array_merge($array, $placeholder);
unset($array[$key]);
}
}
var_dump($array);
?>

Checking if array value exists in a PHP multidimensional array

I have the following multidimensional array:
Array ( [0] => Array
( [id] => 1
[name] => Jonah
[points] => 27 )
[1] => Array
( [id] => 2
[name] => Mark
[points] => 34 )
)
I'm currently using a foreach loop to extract the values from the array:
foreach ($result as $key => $sub)
{
...
}
But I was wondering how do I see whether a value within the array already exists.
So for example if I wanted to add another set to the array, but the id is 1 (so the person is Jonah) and their score is 5, can I add the 5 to the already created array value in id 0 instead of creating a new array value?
So after the loop has finished the array will look like this:
Array ( [0] => Array
( [id] => 1
[name] => Jonah
[points] => 32 )
[1] => Array
( [id] => 2
[name] => Mark
[points] => 34 )
)
What about looping over your array, checking for each item if it's id is the one you're looking for ?
$found = false;
foreach ($your_array as $key => $data) {
if ($data['id'] == $the_id_youre_lloking_for) {
// The item has been found => add the new points to the existing ones
$data['points'] += $the_number_of_points;
$found = true;
break; // no need to loop anymore, as we have found the item => exit the loop
}
}
if ($found === false) {
// The id you were looking for has not been found,
// which means the corresponding item is not already present in your array
// => Add a new item to the array
}
you can first store the array with index equal to the id.
for example :
$arr =Array ( [0] => Array
( [id] => 1
[name] => Jonah
[points] => 27 )
[1] => Array
( [id] => 2
[name] => Mark
[points] => 34 )
);
$new = array();
foreach($arr as $value){
$new[$value['id']] = $value;
}
//So now you can check the array $new for if the key exists already
if(array_key_exists(1, $new)){
$new[1]['points'] = 32;
}
Even though the question is answered, I wanted to post my answer. Might come handy to future viewers. You can create new array from this array with filter then from there you can check if value exist on that array or not. You can follow below code. Sample
$arr = array(
0 =>array(
"id"=> 1,
"name"=> "Bangladesh",
"action"=> "27"
),
1 =>array(
"id"=> 2,
"name"=> "Entertainment",
"action"=> "34"
)
);
$new = array();
foreach($arr as $value){
$new[$value['id']] = $value;
}
if(array_key_exists(1, $new)){
echo $new[1]['id'];
}
else {
echo "aaa";
}
//print_r($new);

php - recreate array?

I've "inherited" some data, which I'm trying to clean up. The array is from a database which, apparently, had no keys.
The array itself, is pretty long, so I'm simplifying things for this post...
[0] => Array
(
[id] => 2
[uid] => 130
[eid] => 8
[ename] => Standard
[eaction] => Check
)
[1] => Array
(
[id] => 2
[uid] => 110
[eid] => 8
[ename] => Standard
[eaction] => Check
)
[2] => Array
(
[id] => 2
[uid] => 200
[eid] => 8
[ename] => Standard
[eaction] => Check
)
I'm trying to shift things around so the array is multidimensional and is grouped by ename:
[0] => Array
(
[Standard] => Array
(
[id] => 2
[uid] => 130
[eid] => 8
[eaction] => Check
)
)
[0] => Array
(
[Standard] => Array
(
[id] => 2
[uid] => 130
[eid] => 8
[eaction] => Check
)
)
[0] => Array
(
[Standard] => Array
(
[id] => 2
[uid] => 130
[eid] => 8
[eaction] => Check
)
)
Anyone know how to do something like this?
You can use usort() to sort an array by a user-defined function. That function could compare the ename fields. Then it's just a simple transformation. Like:
usort($array, 'cmp_ename');
function cmp_ename($a, $b) {
return strcmp($a['ename'], $b['ename']);
}
and then:
$output = array();
foreach ($array as $v) {
$ename = $v['ename'];
unset($v['ename']);
$output[] = array($ename => $v);
}
$outputarray = array();
foreach($inputarray as $value) {
$outputarray[] = array($value['ename'] => $value);
}
would accomplish what your examples seem to indicate (aside from the fact that your 'result' example has multiple things all with key 0... which isn't valid. I'm assuming you meant to number them 0,1,2 et cetera). However, I have to wonder what benefit you're getting from this, since all it appears to be doing is adding another dimension that serves no purpose. Perhaps you could clarify your example if there are other things to take into account?
$outputarray = array();
foreach($inputarray as &$value) {
$outputarray[][$value['ename']] = $value;
unset($value['ename']);
} unset($value);
I'm guessing that this is what you're asking for:
function array_group_by($input, $field) {
$out = array();
foreach ($input as $row) {
if (!isset($out[$row[$field]])) {
$out[$row[$field]] = array();
}
$out[$row[$field]][] = $row;
}
return $out;
}
And usage:
var_dump(array_group_by($input, 'ename'));
philfreo was right but he was also off a little. with his code every time you encounter an array element with an ['ename'] the same as one you've already gone through it will overwrite the data from the previous element with the same ['ename']
you might want to do something like this:
$output = array();
foreach ($YOURARRAY as $value) {
$output[$value['ename']][] = $value;
}
var_dump($output); // to check out what you get

Categories