How to call an array using a string in PHP - php

I would like to echo a bunch of arrays in numerical order, I tried using WHILE method but lacks the knowledge on how to combine strings to call a variable and get the value inside the array.
$ins1 = array (
"select" => array (
"1" => "1"
),
"note" => array (
"1" => "Message"
)
);
$ins2 = array (
"select" => array (
"1" => "2"
),
"note" => array (
"1" => "Sorry"
)
);
$count = 1;
while($count <= 2){
$ins = '$ins'.$count;
echo $ins["select"][$count] .' '. $ins["note"][$count].'<br>';
$count++;
}
OUTPUT SHOULD BE:
1 Message
2 Sorry

What you're looking for is "Variable variables", through which you can set the variable name dynamically; so to get what you want, change your code as the following:
$count = 1;
while($count <= 2){
$ins = 'ins'.$count;
$var = $$ins; // now your $var is either $ins1 or $ins2 :)
echo $var["select"][1] .' '. $var["note"][1].'<br>';
$count++;
}
The output would be:
1 Message
2 Sorry

You should have combined the two variable, and make life easier:
$ins = [
[//$ins1
"select" => array ("1" => "1"),
"note" => array ("1" => "Message" )
],
[//$ins2
"select" => array ("1" => "2"),
"note" => array ("1" => "Sorry")
]
];
for ($i = 0; $i < count($ins); $i++)
{
echo $ins[$i]["select"][1]." ".$ins[$i]["note"][1]."<br/>";
}
for dynamic name of variables, see other answers.. hope i've helped you.. Cheers! ;)

this will do the trick for you:
$ins1 = array (
"select" => array (
"1" => "1"
),
"note" => array (
"1" => "Message"
)
);
$ins2 = array (
"select" => array (
"1" => "2"
),
"note" => array (
"1" => "Sorry"
)
);
for($i=1; $i<1000; $i++) {
$arr_name = 'ins'.$i;
if(isset($$arr_name)) {
$str = '';
foreach ($$arr_name as $key => $value) {
$str .= $value[1].' ';
}
echo trim($str).'<br/>';
} else {
break;
}
}
Note: I have taken 1000 as a highest possible value, you can change accordingly. like in your case it is 2.

Related

How do I compare these two Arrays for sameness?

I have an array consisting of seat number in the following format
<?php
$seatnumbers = array(
"A1" => "1","A2" => "2",
"B1" => "3","B2" => "4","B3" => "5",
"C1" => "6","C2" => "7","C3" => "8",
"D1" => "9","D2" => "10","D3" => "11",
"E1" => "12","E2" => "13","E3" => "14"
);
?>
And also the retrieved data of reserved seats by users which comes in this format
<?php
$seat = array();
$sql = $db->query("SELECT booked_seat FROM mybooking where bus_id = '{$l}'");
$row = $sql->fetchAll(PDO::FETCH_ASSOC);
foreach($row as $r){
$seat[] = $r['booked_seat'];
}
print_r($seat)
// Array ( [0] => A1 [1] => D2 )
?>
All I am trying to achieve is to disable the selected seats in a HTML select like I tried doing here
<?php
$keys = array_keys($seatnumbers);
$values = array_values($seatnumbers);
$skeys = array_keys($seat);
$val = array_values($seat);
for($i = 0; $i < 14; $i++ )
{
if($keys[$i] == $val[$i]){
echo "<option disabled>". $keys[$i]. "(Booked)</option>";
}else{
echo "<option value='".$keys[$i]."'>". $keys[$i]."-". $val[$i]. "(Available)</option>";
}
}
?>
But only the first option showed booked. How do compare for two arrays to disabled the reserved seats.
Here is the result of what I tried
Using prepared statements and also using PDO::FETCH_COLUMN to save having to process the result set from the SQL further. The code has comments to show how this is done.
You will have to change the output, but it matches what you have enough to modify it...
$query = "SELECT booked_seat FROM mybooking where bus_id = :busID";
$sql = $db->prepare($query);
$sql->execute(["busID" => $l]);
// Fetch an array with just the values of booked_seat
$seat=$sql->fetchAll(PDO::FETCH_COLUMN, 0);
// Flip array so the seat name becomes the key
$seat = array_flip($seat);
$seatnumbers = array(
"A1" => "1","A2" => "2",
"B1" => "3","B2" => "4","B3" => "5",
"C1" => "6","C2" => "7","C3" => "8",
"D1" => "9","D2" => "10","D3" => "11",
"E1" => "12","E2" => "13","E3" => "14"
);
foreach ( $seatnumbers as $seatName => $number ) {
echo $seatName;
// If the key is set in the seat array, then it is booked
if ( isset($seat[$seatName]) ){
echo " Seat booked".PHP_EOL;
}
else {
echo " Seat not booked".PHP_EOL;
}
}
This is a typical task for using foreach
<html>
<head></head>
<body>
<?php
$seatnumbers = array(
"A1" => "1","A2" => "2",
"B1" => "3","B2" => "4","B3" => "5",
"C1" => "6","C2" => "7","C3" => "8",
"D1" => "9","D2" => "10","D3" => "11",
"E1" => "12","E2" => "13","E3" => "14"
);
$seat = array(
"0" => "A1","1" => "D2",
"2" => "E1","3" => "E2","4" => "E3"
);
echo "<select>";
foreach ($seatnumbers as $ikey=>$ivalue)
{
if(in_array($ikey,$seat)){
echo "<option disabled>". $ikey. "(Booked)</option>";
}else{
echo "<option value='".$keys[$i]."'>". $ikey."-". $val[$i]. "(Available)</option>";
}
}
echo "</select>";
?>
</body>
</html>

How to check whether a value in a key is same for all inner arrays

array will look like
array(
"0" => array(
"name" => "abc",
"age" => 10
)
"1" => array(
"name" => "def",
"age" => 10
)
)
I need to check whether all ages are same in php
You can check like this:
<?php
$arr = array(
"0"=>array(
"name"=>"abc",
"age"=>10,
),
"1"=>array(
"name"=>"def",
"age"=>10,
)
);
if(count($arr)) {
if(count(array_unique(array_column($arr, 'age'))) > 1 && count($arr) > 0) {
echo "Array contains different ages";
} else {
echo "Array contains same ages";
}
} else {
echo "Array has no ages";
}
Output:
Array contains same ages
Here is the eval. Try out there!

PHP - Get key value from other key

I have the following array:
$array = Array(
"0" => Array (
"id" => 1081,
"name" => "John"
),
"1" => Array (
"id" => 1082,
"name" => "Matt"
),
"2" => Array (
"id" => 1083,
"name" => "Roger"
)
);
Is there anyway I can get name if I only know the id but without having to iterate through the array?
For PHP >= 5.5.0:
$id = 1082;
$result = array_column($array, 'name', 'id')[$id];
As Barmar points out, to get an array that is easy to use with id as the index:
$id = 1082;
$result = array_column($array, 'name', 'id');
echo $result[$id];
You can make an associative array that refers to the same elements, then use that:
function make_assoc(&$array, $keyname) {
$new_array = array();
foreach ($array as &$elt) {
$new_array[$elt[$keyname]] = $elt;
}
return $new_array;
}
$assoc_array = make_assoc($array, 'id');
Now you can use $assoc_array[1083] to access the third item in the original array. And since this returns an array of references, modifying that will also modify the element of the original array.
You can use array_map to search into your array if your PHP < 5.5.0 and you don't have array_column:
<?php
$array = Array(
"0" => Array (
"id" => 1081,
"name" => "John"
),
"1" => Array (
"id" => 1082,
"name" => "Matt"
),
"2" => Array (
"id" => 1083,
"name" => "Roger"
)
);
$find = 1082;
$value = '';
$arr = array_map(function($n) use ($find, &$value) {if ($n['id'] == $find) $value = $n['name']; }, $array);
print_r($value);
?>

Multiple values from one loop php

If I have this array -
$data_item['actor_id'] = $this->input->post('actor_id');
$data_item['item_number'] = $this->input->post('item_number');
Which gives me this array -
Array (
[actor_id] => Array (
[0] => 162652153
[1] => 162652154
)
[item_number] => Array (
[0] => 3
[1] => 6
)
)
I need to get my data into this format -
$data = array(
array(
'actor_id' => '3342' ,
'item_number' => '57567'
),
array(
'actor_id' => '876' ,
'item_number' => '94'
)
);
I have tried various ways of looping through it but I can't seem to get it. Such as two seperate loops like this -
foreach($data_item['actor_id'] as $key => $value){
$thevalue[] = array('actor_id' => $value
);
}
But it is wrong format. Any tips please?
What about:
$d = [
'actor_id' => [
1,
2,
],
'item_number' => [
3,
4,
],
];
$res = [];
foreach ( $d as $key => $data ) {
foreach ( $data as $index => $value ) {
$res [ $index ] [$key] = $value;
}
}
I'll generate:
array(2) {
[0]=>
array(2) {
["actor_id"]=>
int(1)
["item_number"]=>
int(3)
}
[1]=>
array(2) {
["actor_id"]=>
int(2)
["item_number"]=>
int(4)
}
}
HTH
you can make use of the actor_id keys to flatten your data as desired:
$data = array(); // your new array
foreach($data_item['actor_id'] as $key => $value) {
// make sure we have an array for this key and add actor id
if (!isset($data[$key])) $data[$key] = array();
$data[$key]['actor_id'] = $value;
// now check if we have an item number for this key and add it
if (isset($data_item['item_number'][$key]))
$data[$key]['item_number'] = $data_item['item_number'][$key];
}
print_r($data);
The result should print out just as you wanted it. Sorry for not having tested the code my self, just typed it out of my head missing time and interpreter right now :)

remove complete level of an array

im trying to remove a complete level in an array
all the items starting with [1]
i am having no luck with arrays at all. kinda new to me. and reading all the stuff i find is not clear nor example like mine.
heres my code so far. i can remove the submit. but i cant go any farther plus im not sure how to remove all of them in heading,special,item, etc as item [1] - regular caesar salad
thank you for any help you may provide
code
<?php
// version:
$testarray =
Array(
"heading" => Array
(
"0" => 'Salads',
"1" => 'Salads',
"2" => 'Pasta',
),
"special" => Array
(
"0" => '',
"1" => '',
"2" => '',
),
"item" => Array
(
"0" => 'Small Green',
"1" => 'Regular Caesar',
"2" => 'Baked Lasagna',
),
"description" => Array
(
"0" => 'Grape tomatoes, onions, green peppers and cucumbers on the bed of crisp lettuce.',
"1" => 'Classic recipe with romaine lettuce and croutons',
"2" => 'With meat sauce, tomato vegetarian sauce or Alfredo sauce',
),
"price" => Array
(
"0" => 'See Desc',
"1" => '$5.99',
"2" => '$9.69',
),
"notes" => Array
(
"0" => 'Available in Small ($2.99), Regular ($5.99)',
"1" => '',
"2" => '',
),
"submit_val" => 'Submit'
);
echo "testarray";
echo "<pre>";
print_r($testarray);
echo "</pre>";
echo "<hr>";
$removed_data=removeItem($testarray,'Submit');
echo "removed_data";
echo "<pre>";
print_r($removed_data);
echo "</pre>";
echo "<hr>";
die();
// works for submit
function removeItem($look_in_Array, $remove){
foreach($look_in_Array as $key => $value) {
echo $key . ' = ' . $value . '<br>';
if ($value ==$remove) {
echo 'found '.$remove."<br>";
unset($look_in_Array[$key]);
}
}
return $look_in_Array;
}
?>
output desired?:
sample of desired output
$testarray =
Array(
"heading" => Array
(
"0" => 'Salads',
"1" => 'Pasta',
),
"special" => Array
(
"0" => '',
"1" => '',
),
"item" => Array
(
"0" => 'Small Green',
"1" => 'Baked Lasagna',
),
"description" => Array
(
"0" => 'Grape tomatoes, onions, green peppers and cucumbers on the bed of crisp lettuce.',
"1" => 'With meat sauce, tomato vegetarian sauce or Alfredo sauce',
),
"price" => Array
(
"0" => 'See Desc',
"1" => '$9.69',
),
"notes" => Array
(
"0" => 'Available in Small ($2.99), Regular ($5.99)',
"1" => '',
),
"submit_val" => 'Submit'
);
If I understand your question correctly, you're looking to remove any array key [1]. If you're doing this as a function anyway, you can either use unset or declare and return a new array. Using unset() might be what you're looking for, but it is sort of a waste of time in a function because it only passes a local variable. Instead, you may want to pass values onto a new array. Please note that this will retain key values.
function removeItemsRecursive($array,$searchKey) {
/*
** Finds any key value that equals $searchKey
** in a multi-level array and does not pass anything
** equal to $searchKey.
*/
foreach($array AS $key=>$value) { //go through each array and assign [key] => value to $key and $value, respectively
if($key !== $searchKey) //if a key is not equal to the $searchKey (aka 1 for example) then assign something to $newArray
{
if(is_array($value)) //if the value inside of the array is another array (for multilevel arrays)
{
$newArray[$key] = removeItemsRecursive($value,$searchKey); //loop through the function and do this for the next level down.
}
else //if the value inside of the array is scalar
{
$newArray[] = $array[$key]; //the new array is assigned the current value where the array key is not equal to $searchKey.
}
}
}
return $newArray;
}
This will essentially go through each value of the $array and pass that value to $newArray if the $key is not $searchKey, aka removeItemsRecursive($array,1); will return a new array without any values with the key being 1.
Calling the Function
To call the function, simply add:
$array = removeItemsRecursive($testarray,1);
When looking at this new array, you will see the results you're looking for.
echo "<PRE>";
print_r($array);
echo "</PRE>";
//returns the array you're looking for.
http://php.net/manual/en/function.unset.php
use unset function in php. in your case you could just iterate over the array and remove all the element at position 1.
function removeLevel($a, $l) { // $a = entire array, $l = level to remove
$removed = array();
foreach ($a as $inner) { // iterate through the outer array
array_splice($inner,$l,1); // remove the "$l"th element of the $inner array
}
return $a; // return new array with level removed
}
$arrBetter = removeLevel($testarray, 2) will return the array with that level of data removed!

Categories