php array index entries auto populate - php

I have two arrays
$arrayOne = ( [0] => 4892 [1] => 98508 [2] => 7834 [3] => 47826 )
$arrayTwo = ( [1] => Car [2] => Computer )
Notice the elements of arrayTwo does not start at 0, but which is what i want because it will be used to pair with arrayOne, ie. Car matches with 98508.
I want to populate the second array where there are no entries with a string for example arrayTwo output:
$arrayTwo = ([0] => its empty [1] => Car [2] => Computer [3] => its empty
How can i achieve this desired output?

Loop the first and check for the key. If it doesn't exist, set it:
foreach($arrayOne as $key => $val) {
if(!isset($arrayTwo[$key])) { $arrayTwo[$key] = 'its empty'; }
}

foreach ($arrayOne as $key => $value){
if (!array_key_exists($key, $arrayTwo)){
$arrayTwo[$key] = 'its empty';
}
}

Related

Delete array from nested array

How can I delete the first Name arrray
[0] => Array
(
[Name] => John
)
from this one just if exist at lest two Name objects?
Array
(
[0] => Array
(
[Name] => John
)
[1] => Array
(
[Name] => James
)
[2] => Array
(
[Surname] => Doe
)
)
I'm trying to go through array with foreach, count how many arrays has name object and if there is more than one, then unset the first, but I'm not able to do that:
foreach($endArray as $arr)
{
if(count($arr['Name'])>1)
{
unset($endArray[0]);
}
}
In your code you use if(count($arr['Name'])>1) but I think that will never be true as the count will return 1 when the value is neither an array nor an object with implemented Countable interface.
To unset the first when there are more than one, you could count the number of occurrences of "Name" in the items using array_column.
If you want to remove the first array which has a key "Name" you could loop over the items and use unset using the $key.
Then break the loop to only remove the first encounter item.
$endArray = [
["Name" => "John"],
["Name" => "James"],
["Name" => "Doe"]
];
if (count(array_column($endArray, 'Name')) > 1) {
foreach ($endArray as $key => $arr) {
if (array_key_exists('Name', $arr)) {
unset($endArray[$key]);
break;
}
}
}
print_r($endArray);
Php demo
Output
Array
(
[1] => Array
(
[Name] => James
)
[2] => Array
(
[Name] => Doe
)
)
Another option is to keep track of the number of times the "Name" has been encountered:
$count = 0;
foreach ($endArray as $key => $arr) {
if (array_key_exists('Name', $arr) && $count === 0) {
$count++;
} else {
unset($endArray[$key]);
break;
}
}
Php demo

How to sum value of array if some values are same?

I have following array
Array (
[0] => 1995,17500
[1] => 2052,17500
[2] => 2052,17500
[3] => 2236,30000
[4] => 2235,15000
[5] => 2235,40000
);
I have exploded the value with comma ,.
foreach($array as $key=>$value) {
$newar = explode(',', $value);
}
So I have similar first value i.e $newar["0"]. For example 2235 and 2052. And I would like to have sum of second value i.e $newar["1"].
How can I achieve following result with PHP.
Array (
[0] => 1995, 17500
[1] => 2052, 35000
[2] => 2036, 30000
[3] => 2235, 55000
)
You can create a new array key/index based and use array_key_exists to check if the key already exists. If so sum the value, if not create the key. This is not the exact result you want, but it's neater.
$newar = []; //New Array
foreach($array as $value) {
$explArr = explode(',', $value);
if(array_key_exists($explArr[0], $newar)){ //Check if the key already exists
$newar[$explArr[0]] += $explArr[1]; //Sum value to existing key
} else {
$newar[$explArr[0]] = $explArr[1]; //Create key
}
}
Your result array will look like this:
Array (
[1995] => 17500
[2052] => 35000
[2036] => 30000
[2235] => 55000
)

php - rearranging an array into groups

I have an array of filenames:
Array
(
[2] => 1_1_page2-img1.jpg
[3] => 1_2_page2-img1-big.jpg
[4] => 2_1_page2-img1.jpg
[5] => 2_2_page2-img1-big.jpg
[6] => 3_1_page2-img1.jpg
[7] => 4_1_page2-img1.jpg
[8] => 4_2_page2-img1.jpg
[9] => 5_2_page2-img1.jpg
)
I'm trying to rearrange them so they're grouped together by their first number. I'm guessing I could maybe separate them with a pipe so I could then distinguish them afterwards. Either that or a multidimensional array.
I know I can perform an explode("_",$filename); to get the first and second digits before the underscores.
The catch is even though the beginning numbers should always increment, there won't necessarily be 2 files per initial number.
So I'm either trying to make it into the following:
Array
(
[0] => 1_1_page2-img1.jpg|1_2_page2-img1-big.jpg
[1] => 2_1_page2-img1.jpg|2_2_page2-img1-big.jpg
[2] => 3_1_page2-img1.jpg|
[3] => 4_1_page2-img1.jpg|4_2_page2-img1.jpg
[4] => |5_2_page2-img1.jpg
)
Or something a bit tidier perhaps? I just can't work out the foreach to put them together.
Or is there an array related command that will put them together easier?
My preference would be to store them in subarrays, as this will be much easier to deal with in the long run; so this would be a possibility, given your array is in $arr:
$newarr = array ();
while (list($key, $val) = each($arr)) {
$subarray_index = substr($val, 0, strpos($val, "_"));
$newarr[$subarray_index][] = $val;
}
Is this what you mean?
$arr = Array(
2 => '1_1_page2-img1.jpg',
3 => '1_2_page2-img1-big.jpg',
4 => '2_1_page2-img1.jpg',
5 => '2_2_page2-img1-big.jpg',
6 => '3_1_page2-img1.jpg',
7 => '4_1_page2-img1.jpg',
8 => '4_2_page2-img1.jpg',
9 => '5_2_page2-img1.jpg'
);
function orderArray($pArr){
$first = '0';
$newArr = array();
foreach($pArr as $val){
if(strpos($val,$first) !== 0){
if(substr($val,2,1)==='1'){
$newArr[]=$val;
}else{
$newArr[]='|'.$val;
}
$first = substr($val,0,1);
}else{
$curIndex = count($newArr) - 1;
$newArr[$curIndex] = $newArr[$curIndex].'|'.$val;
}
return $newArr;
}
$result = orderArray($arr);
print "number of values: ".count($result)."<br>";
foreach($result as $value){
print $value."<br>";
}
Just worked it out now based on another post in stackoverflow:
foreach ($scanned_directory as $filename){
$ids = explode("_",$filename);
$groups[$ids[0]][] = $filename;
}
echo "<pre>";
ksort($groups);
print_r($groups);
echo "</pre>";
Displays:
Array
(
[1] => Array
(
[0] => 1_1_page2-img1.jpg
[1] => 1_2_page2-img1-big.jpg
)
[2] => Array
(
[0] => 2_1_page2-img1.jpg
[1] => 2_2_page2-img1-big.jpg
)
[3] => Array
(
[0] => 3_1_page2-img1.jpg
[1] => 3_2_page2-img1-big.jpg
)
[10] => Array
(
[0] => 10_1_page2-img1.jpg
)
[11] => Array
(
[0] => 11_2_page2-img1-big.jpg
)
)
There isn't a nice automated way of doing this, but you could use a simple loop:
$array = [];
foreach ($filename as $file) {
$fields = explode('_', $file);
$array[$fields[0]][$fields[1]] = $file;
}
An example is located here.

Convert complex numerical array to associative array

I have an array data that look like this :
Array (
[0] => Array (
[0] => Name:
[1] => John W.
[2] => Registration ID:
[3] => 36
)
[1] => Array (
[0] =>Age:
[1] => 35
[2] => Height:
[3] => 5'11"
)
[3] => Array (
[0] => Sex:
[1] => M
[2] => Weight:
[3] => 200lbs
)
[4] => Array (
[0] => Address
)
[5] => Array (
[0] => 6824 crestwood dr delphi, IN 46923
))
And I want to convert it to associative array like this :
Array(
['Name']=> John W.
['Registration ID']=> 36
['Age']=> 35
['Height'] => 5'11''
['Sex']=>M
['Weight']=>200lbs
['Address']=>6824 crestwood dr delphi, IN 46923
)
I have no idea at all how to do this, since the supposed to be array column header were also in sequence, so it makes difficult to convert this array.
Any help I appreciate, thx.
Given your origin array is called $origin , you can do it like this:
$merged = array();
foreach($origin as $val) {
$merged = array_merge($merged, $val);
}
$tot = count($merged) - 1;
for ($i=0;$i<$tot;$i+=2) {
$result[$merged[$i]] = $merged[$i+1];
}
var_dump($result); // To test the resulting array
Firstly, I use array_merge() to flatten the $origin array to only one dimension/depth, so we later iterate it (stepping each 2 items per iteration) and assigning each pair of items ($i and $i+1) to the resulting array.
Looks like, for the first 3 children, you can just assign the even value to the previous element as key. Then, assign the fourth one as key for fifth element.
$result = array();
foreach ($array as $key => $value)
{
if ($key < 4) {
$elements = array_values($value);
$result[$elements[0]] = $elements[1];
$result[$elements[2]] = $elements[3];
}
if ($key == 4)
$fifthkey = $value;
if ($key == 5)
$result[$fifthkey] = $value;
}
Also, note that you have to escape your height string quotes.

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);

Categories