How to define a custom key in PHP arrays? [closed] - php

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to define a two dimension array like below:
[40.1][John]
[40.2][Jane]
[40.7][Mary]
[40.10][Sara]
in other words I want to define an array with custom key. Later I need to access to the array values with the custom key. for instance :
echo(myarray[40.2]);
And I need to generate the array dynamically from XML , since the values are coming from a XML file.
The XML file which I want to generate the array from is like below:
<rules>
<rule>
<id>40.1</id>
<regex><![CDATA[/(?:\)\s*when\s*\d+\s*then)/]]></regex>
</rule>
<rule>
<id>40.2</id>
<regex><![CDATA[/(?:"\s*(?:#|--|{))/]]></regex>
</rule>
How should I create the array with above characteristics?

You can do this very easily by creating an associative array
$myarray = array(
"40.1" => "John",
"40.2" => "Jane",
"40.7" => "Mary",
"40.10" => "Sara"
);
Later on you can iterate over this array with a foreach loop
foreach($myarray as $key => $value) {
echo "<p>" . $key . " = " . $value . "</p>";
}
This will output to the screen
40.1 = John
40.2 = Jane
40.7 = Mary
40.10 = Sara
To create a new array and add items to is as easy as doing this
$myarray = array();
$myarray[$newkey] = $newvalue;
For a two dimensional array, you can define them like this
$myarray = array();
$myarray[$key] = array();
$myarray[$key]['John'] = 'some value';
$myarray[$key]['Jane'] = 'another value';
$myarray[$key2] = array();
$myarray[$key2]['Mary']= 'yet another value';
Or as a short cut
$myarray = array(
$key => array(
'John' => 'some value',
'Jane' => 'another value',
),
$key2 = array(
'Mary' => 'yet another value'
)
);

You can do it with associative array key => value.
$arr = array('40.1' => 'John', '40.2' => 'Jane', '40.7' => 'Mary', ...);
echo $arr['40.1']; // will return John
If you think to extend the data in the feature, you can do it with nested arrays
$arr = array(
'40.1' => array('name' => 'John', 'eyes' => 'green');
'40.2' => array('name' => 'Jane', 'eyes' => 'blue');
);
You can access nested array like this:
echo $arr['40.2']['eyes'] // return blue
You can see also PHP documentation about arrays here

Array keys
Notice! Do not use "float" as type for array keys.
<?php
$array = array(
1 => "a",
"1" => "b",
1.5 => "c",
true => "d",
);
var_dump($array);
Output will be:
array(1) {
[1]=>
string(1) "d"
}
Taken from http://www.php.net/manual/en/language.types.array.php.
Two-dimensional arrays
You can create your array like this:
$data = [
'40.2' => [
'John' => [
// and now this is second dimension
]
]
];
Add aditional stuff:
$data['40.2']['John'][] = ; // just append value
// or
$data['40.2']['John']['sex'] = 'Male'; // store it with key
Or if you need to store scalar values, you can define array like this:
$data = [
'40.2' => [
'John' => 'male' // storing scalar values
]
];
Sorry, If I misunderstood your question.

Related

Removing unwanted key/value pair in php array? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
$data = array("0"=>"1","id"=>"1","1"=>"mani","name"=>"mani","2"=>"ssss","lname"=>"ssss");
above is my output but i want an array like below format. Please help me.
Correct Output:
$data = array ("id"=>"1","name"=>"mani","lname"=>"ssss");
check this, use is is_numeric to check number or string.
$data = array("0"=>"1","id"=>"1","1"=>"mani","name"=>"mani","2"=>"ssss","lname"=>"ssss");
foreach ($data as $key => $val)
{
if(!is_numeric($key))
{
$new_array[$key] = $val;
}
}
print_r($new_array);
OUTPUT :
Array
(
[id] => 1
[name] => mani
[lname] => ssss
)
DEMO
The Code-Snippet below contains Self-Explanatory Comments. It might be of help:
<?php
// SEEMS LIKE YOU WANT TO REMOVE ITEMS WITH NUMERIC INDEXES...
$data = array( "0" => "1",
"id" => "1",
"1" => "mani",
"name" => "mani",
"2" => "ssss",
"lname"=> "ssss"
);
// SO WE CREATE 2 VARIABLES TO HOLD THE RANGE OF INTEGERS
// TO BE USED TO GENERATE A RANGE OF ARRAY OF NUMBERS
$startNum = 0; //<== START-NUMBER FOR OUR RANGE FUNCTION
$endNum = 10; //<== END-NUMBER FOR OUR RANGE FUNCTION
// GENERATE THE RANGE AND ASSIGN IT TO A VARIABLE
$arrNum = range($startNum, $endNum);
// CREATE A NEW ARRAY TO HOLD THE WANTED ARRAY ITEMS
$newData = array();
// LOOP THROUGH THE ARRAY... CHECK WITH EACH ITERATION
// IF THE KEY IS NUMERIC... (COMPARING IT WITH OUR RANGE-GENERATED ARRAY)
foreach($data as $key=>$value){
if(!array_key_exists($key, $arrNum)){
// IF THE KEY IS NOT SOMEHOW PSEUDO-NUMERIC,
// PUSH IT TO THE ARRAY OF WANTED ITEMS... $newData
$newData[$key] = $value;
}
}
// TRY DUMPING THE NEWLY CREATED ARRAY:
var_dump($newData);
// YIELDS::
array (size=3)
'id' => string '1' (length=1)
'name' => string 'mani' (length=4)
'lname' => string 'ssss' (length=4)
Or even concisely, you may walk the Array like so:
<?php
$data = array(
"0" => "1",
"id" => "1",
"1" => "mani",
"name" => "mani",
"2" => "ssss",
"lname" => "ssss"
);
array_walk($data, function($value, $index) use(&$data) {
if(is_numeric($index)){
unset($data[$index]);
}
});
var_dump($data);
// YIELDS::
array (size=3)
'id' => string '1' (length=1)
'name' => string 'mani' (length=4)
'lname' => string 'ssss' (length=4)
$data = array("0"=>"1","id"=>"1","1"=>"mani","name"=>"mani","2"=>"ssss","lname"=>"ssss");
$new_data = array();
foreach($data as $k => $v)
if(strlen($k)>1) $new_data[$k] = $v;
print_r($new_data);
I'm a little confused as to what exactly you're looking for. You give examples of output, but they look like code. If you want your output to look like code you're going to need to be clearer.
Looking at tutorials and documentation will do you alot of good in the long run. PHP.net is a great resource and the array documentation should help you out alot with this: http://php.net/manual/en/function.array.php

Php, remove key from an array red-handed

I want to remove an item from an array. I can write this:
$item = array(
'id' => 1
'name' => 'name'
);
$item2 = $item;
unset($item2['id']);
$names[] = $item2;
but the last 3 lines are somewhat "cumbersome", soo un elegant. Can it be solved without creating $item2 ? Something like:
$item = array(
'id' => 1
'name' => 'name'
);
$names[] = array_ignore_index('id', $item);
From your codes, I can see that you are trying to get the names[] from item array. One possible simple solution for this specific scenario:
For example IF you have :
$items = array(
array(
//this is your item 1
'id' => 1,
'name' => 'name1'
),
array(
//this is item 2
'id' => 2,
'name' => 'name2'
)
);
and you want to retrieve the names in the names array.
You can just do:
$names = array_column($items, 'name');
It will return:
Array
(
[0] => "name1"
[1] => "name2"
)
Please note this solution is best fit for this specific scenario, it may not fit your current scenario depending.
The shortest out of the box solution is to create a diff of the array keys:
$names[] = array_diff_key($item, array_flip(['id']));
See http://php.net/array_diff_key.
function array_ignore_index($id,$item){ ///function
unset($item[$id]);
return $item;
}
$a=array('id'=>1,
'name'=>'name');
$b=array_ignore_index('name',$a);
echo $b['name']; //create error id is not present
Here is the code for required operation..
You can use unset array column
Code is
unset($item['id']);
To test it
print_r($item);

Search for key and value in php arrays

So I have two array, the first one is like:
$MyArray = [
['id' => 1, number => 32],
['id' => 2, number => 4]
];
and the other is like:
$OtherArray = [
['id' => 1, 'show' => X],
['id' => 5, 'show' => X]
];
Where is X, I want it to be equal with the 'number' value of $MyArray where key 'id' = its id.
If there is no $MyArray.id which is equal to $OtherArray.id then it should return 0.
I hope you understand what I mean. I tried everything, what I could, yet, with no success.
Have you tried using a foreach loop here?
Here is a quick example... PHPaste Snippet
<?php
$firstArray = array(
array(
"id" => 1,
"something" => "Hello, World!"
),
array(
"id" => 3, // 3 on purpose
"something" => "Hello, mom?"
)
);
$secondArray = array(
array(
"id" => 1,
"thing" => null
),
array(
"id" => 2,
"thing" => null
)
);
foreach ($firstArray as $key => $value) {
foreach ($secondArray as $k => $v) {
if ($value['id'] == $v['id']) {
echo "Found one!\n------\n" . print_r($value, true) . "\ncontains the same ID as\n\n" . print_r($v, true) . "\n------\n";
// you may also do this if you want
// $secondArray[$k]['thing'] = $value['id'];
// this would set "thing" (in the second array) to the value of "id" (in the first array)
}
}
}
EDIT Here is a second example, displaying how you could use it as a function... PHPaste Snippet.
Note: I used the OLD array syntax because it's easier for new programmers to understand.
So, essentially what you are doing is iterating through each item in $firstArray, comparing it to each item in $secondArray, by doing a nested foreach within side the first foreach if that makes sense...?
Here is what I just said in simple form:
go through each item in array 1
--> compare it to each item in array 2
You may also notice my use of PHP's lovely function, print_r(). This displays objects and arrays in a slightly, clearer, form.
You can also see that I am getting the values from within the arrays by using $value['id'] and $v['id']. These were defined in my foreach declaration, foreach ($firstArray as $key => $value); $value is an associative array, so you can simply get a value by key just as you would if you created an array like this:
$myArray = [
"id" => 1
];
and grabbed values like this:
echo $myArray['id']; // 1
Hopefully this helped.

Simple PHP array for storing text?

I'm trying to learn some basic PHP but am running into some confusion around using arrays.
I have three "pools" of words. 20 words in each pool for a total of 60 words.
I need to store these in separate arrays, and then pull out a random selection from the array on click of a button. So each time the button is clicked, another four will be pulled from my array of 20 entries.
You can see my non-functioning page here: http://francesca-designed.me/create-a-status/
So the words on the side, when you click the button it'd run through the 20 words in the array and output them in each span, just four each time you click the button.
I looked on the PHP site and found this but I'm confused about which one to use.
Ultimately I would like to add this to a database as in the end if will be 50 words per pool, but for now I want to keep it all in one place while I practice.
<?php
$fruits = array (
"fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second", "third")
);
?>
There are two types of arrays:
array(
'key' => 'value',
'key' => 'value',
'key' => 'value',
)
and
array(
'value',
'value',
'value',
'value',
);
the latter is the same as:
array(
0 => 'value',
1 => 'value',
2 => 'value',
3 => 'value',
);
it's really how you want to use them...
if you loop through them with
foreach($array as $value) {
}
or
foreach($array as $key => $value) {
}
and there is no need for named keys, just use the second array.
edit:
$array = array(
'one' => array ('qwe1rty1','qwe1rty2','qwe1rty3'),
'two' => array ('qwe2rty1','qwe2rty2','qwe2rty3'),
'three' => array ('qwe3rty1','qwe3rty2','qwe3ert3'),
);
$array['one'][2] === 'qwe1rty3' (index starts at 0)
$array['three'][0] === 'qwe3rty1'
foreach($array['one'] as $key => $value) {
echo $key .' : ' $value;
}
gives
0 : qwe1rty1
1 : qwe1rty2
2 : qwe1rty3
Here is an example that is similar to what you're describing:
$words = array("tasty", "wretched", "simple", "gnarly", "fruitful", "cleeeever");
echo $words[1]; //prints wretched
for($i=0;$i<4;$i++) {//prints array in original order
echo $words[$i].'<br/>';
}
shuffle($words);
for($i=0;$i<4;$i++) {//prints shuffled array
echo $words[$i].'<br/>';
}

Transform string from associative array into multidimensional array

I'm storing images links into the database separating them with ,, but I want to transform this string into an array, but I'm not sure how to do it.
So my array looks like this:
$array = array(
"name" => "Daniel",
"urls" => "http:/localhost/img/first.png,http://localhost/img/second.png"
);
So I'd like to have it in the following form:
$array2 = array(
"name" => "Daniel",
"urls" => array("http:/localhost/img/first.png",
"http://localhost/img/second.png" )
);
I haven't been PHP'ing for a while, but for that simple use-case I would use explode.
$array['urls'] = explode(',', $array['urls']);
Uncertain if I interpreted your question correct though?
You can use array_walk_recursive like in the following example.
function url(&$v,$k)
{
if($k=='urls') {
$v = explode(",",$v);
}
}
$array = array(
"name" => "Daniel",
"urls" => "http:/localhost/img/first.png,http://localhost/img/second.png"
);
array_walk_recursive($array,"url");
You can check the output on PHP Sandbox

Categories