get key of multi dimension array (PHP Language) - php

Hi I have a problem regarding multi-dimension array. I have a set of array looking like this
array:3 [▼
0 => array:1 [▼
"tree" => "0"
]
1 => array:1 [▼
"tree" => "2"
]
2 => array:1 [▼
"tree" => "0"
]
]
the array is from
dd($this->treeArray);
how do I want to get the array which the value is 0. Expected result/filter
For example:
array:2 [▼
0 => array:1 [▼
"tree" => "0"
]
1 => array:1 [▼
"tree" => "0"
]
]
or
array:1 [▼
0 => array:1 [▼
"tree" => "2"
]
]
if changing the index is impossible, its ok..
Thank you

As you are using Laravel, you could use array helper such as this
You can use like this:
use Illuminate\Support\Arr;
$newTreeArray = Arr::where($this->treeArray, function ($tree) => $tree['tree'] === "0");

do you want in_array()?
$arraysContainingZero=[];
foreach($this->treeArray as $wutkey => $wut){
if(in_array("0", $wut, true)){
$arraysContainingZero[$wutkey] = $wut;
}
}
var_dump($arraysContainingZero);

There are a lots of build in function in PHP that is useful for operating on an array. You can see the full list here: https://www.php.net/manual/en/ref.array.php
One of the function is called array_filter (https://www.php.net/manual/en/function.array-filter.php). The function iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array.
So in your case, you want to call the array_filter with a callback that return true if the value is 0. Example:
$input = [
[ 'tree' => 1 ],
[ 'tree' => 0 ],
[ 'tree' => 0 ],
];
$output = array_filter($input, function($arr) {
return $arr['tree'] === 0;
});
var_dump($output);
// result
array(2) {
[1]=>
array(1) {
["tree"]=>
int(0)
}
[2]=>
array(1) {
["tree"]=>
int(0)
}
}

Related

How to check that element in array are all same in twig?

I have following array:
array:3 [▼
0 => "1234"
1 => "1234"
2 => "1234"
]
In twig I want to check if all element are same return true else return false.

Filter Array based on if contains php

My aim here is to remove the whole object from the array if "record_type" is null. I should then only be left with data that has a record_type set in the array.
I've looked into the array filter not sure how I target the data within the array "record_type". My only other thought is to import to a database and then SQL query what I want then delete data I've had which is much more overkill.
<pre>
array:36 [▼
0 => array:3 [▼
"type" => "comment"
"line_index" => 0
"text_b64" => "OyBjUGFuZWwgZmlyc3Q6ODguMC4xMiAodXBkYXRlX3RpbWUpOjE2MTg1NDYxNDIgQ3BhbmVsOjpab25lRmlsZTo6VkVSU0lPTjoxLjMgaG9zdG5hbWU6cjExOC5sb24yLm15c2VjdXJlY2xvdWRob3N0LmNvbSBs ▶"
]
1 => array:3 [▼
"line_index" => 1
"text_b64" => "OyBab25lIGZpbGUgZm9yIG9ha3RyZWVkZW50YWxtb3J0aW1lci5jby51aw=="
"type" => "comment"
]
2 => array:3 [▼
"text_b64" => "JFRUTCAxNDQwMA=="
"line_index" => 2
"type" => "control"
]
3 => array:6 [▼
"line_index" => 3
"dname_b64" => "b2FrdHJlZWRlbnRhbG1vcnRpbWVyLmNvLnVrLg=="
"record_type" => "SOA"
"ttl" => 30
"type" => "record"
"data_b64" => array:7 [▶]
]
4 => array:6 [▼
"dname_b64" => "b2FrdHJlZWRlbnRhbG1vcnRpbWVyLmNvLnVrLg=="
"line_index" => 10
"record_type" => "NS"
"ttl" => 30
"type" => "record"
"data_b64" => array:1 [▶]
]
5 => array:6 [▼
"ttl" => 30
"dname_b64" => "b2FrdHJlZWRlbnRhbG1vcnRpbWVyLmNvLnVrLg=="
"line_index" => 11
"record_type" => "NS"
"data_b64" => array:1 [▶]
"type" => "record"
]
</pre>
Goal: only be left with data that has a 'record_type' set (not null) in the array
Solution: use array_filter() on your source array ($arr) and filter for records with 'record_type' != "NS" (assuming "NS" is what you refer to as null, or not set).
<?php
$result = array_filter(
$arr,
function (array $record) {
if (isset($record['record_type'])) {
return $record['record_type'] != "NS";
} return null;
}
);
working demo
EDIT
If you want to filter for only those records that are of a certain type, e.g. type 'record', following should help:
<?php
$result = array_filter(
$arr,
function (array $record) {
if ($record['type'] == 'record') {
return true;
} return false;
}
);
working demo
If your Goal is to filter array to remove any inner-array that hasn't a record_type, So use array_filter with a callback function fn to check that record_type exist with isset function.
array_filter($arr, fn($el)=>isset($el["record_type"]));

Array of Arrays returning non-sense when running in foreach

My project has an array made of a request with an array of inputs inside, as it follows:
array:8 [▼
"type_id" => array:1 [▼
0 => "1"
]
"zip_code" => array:1 [▼
0 => "88801500"
]
"street_address" => array:1 [▼
0 => "Avenida Getúlio Vargas"
]
"number" => array:1 [▼
0 => "asdasd"
]
"street_address_2" => array:1 [▼
0 => "asdasd"
]
"city_id" => array:1 [▼
0 => "4384"
]
"neighborhood" => array:1 [▼
0 => "Centro"
]
"created_by" => 2
]
But when I try to run said array on a foreach to insert it on the database, I get a result that doesnt make sense:
array:1 [▼
0 => "1"
]
My code:
dd($dataEnderecos); //This is for debug purposes, it shows the initial array on this question.
foreach ($dataEnderecos as $enderecos) {
dd($enderecos); //This is for debug purposes, it shows the secondary array on this question.
$enderecoID = $this->address->create($enderecos)->id;
$this->repository->enderecos()->attach($enderecoID);
}
I managed to fix this by using a for loop and using another variable to receive the results of the initial array:
for ($i = 0; $i < $limit; $i++) {
$insert = array(
'type_id' => $dataEnderecos['type_id'][$i],
// ^^^^ ^^^^ ^^^^
// Initial Array Secondary Array Index
);
}

how to get data to save from arrays inside array

i have form to make a bill for multiple products,
that form return request like this
#parameters: array:5 [▼
"quantity" => array:2 [▼
0 => "1"
1 => "2"
]
"product" => array:2 [▼
0 => "Mr. Jasen Beer,OliveDrab,XS"
1 => "Carlotta Yundt"
]
"date" => array:2 [▼
0 => "2019-12-29"
1 => "2019-12-29"
]
"id" => array:2 [▼
0 => "15"
1 => "11"
]
]
}
i need to loop all arrays to make insert all at once
thanks.
Try to loop it like this, you will get the array wrap every product's attributes:
$inserted_array = [];
foreach($parameters as $key => $values) {
foreach($values as $index => $val) {
$inserted_array[$index][$key] = $val;
}
}
\DB::table('table_name')->insert($inserted_array);
And I found that there is id in your array, remember to make it fillable.

How to compare last 2 elements of an array?

I have an array:
array:8 [▼
0 => array:1 [▼
"data" => "789"
]
1 => array:1 [▼
"data" => "800"
]
2 => array:1 [▼
"data" => "789"
]
3 => array:1 [▼
"data" => "787"
]
4 => array:1 [▼
"data" => "787"
]
5 => array:1 [▼
"data" => "787"
]
6 => array:1 [▼
"data" => "787"
]
7 => array:1 [▼
"data" => "787"
]
]
I need to take out the last 2 elements of the array and compare them. I tried using $getLast2 = array_slice($chart_data, -2, 2, true); to get the last 2.
array:2 [▼
6 => array:1 [▼
"data" => "787"
]
7 => array:1 [▼
"data" => "787"
]
]
Which then splits it. But Im not sure how to compare these 2 elements within this new array. As the last 2 elements which are now 6 and 7 could change as more data is added. I basically need to tell if the first element is great than, less than or equal to the second element.
You can use built in end() function and then prev():
if (end($chart_data) == prev($chart_data)) {
echo 'Two last elements of an array are equal!';
}
Pass last variable as false;
preserve_keys
Note that array_slice() will reorder and reset the numeric array indices by default. You can change this behaviour by setting preserve_keys to TRUE.
array_slice($chart_data, -2, 2, false);
You have output this array
array:2 [▼
6 => array:1 [▼
"data" => "787"
]
7 => array:1 [▼
"data" => "787"
]
]
Re-index them to using PHP array_values() function
$outputedArray = array_values($outputedArray)
if($outputedArray[0]['data'] > $outputedArray[1]['data'])
echo "0 index is greater";
If the array you obtained from your previous code is called $splitArray, then you could do the following:
list($array1, $array2) = $splitArray;
if ($array1['data']>$array2['data'])
{
echo "1st is greater than 2nd<br>";
}
else
{
echo "1st is not greater than 2nd<br>";
}
If it suits you, you can just use the array_pop to do the comparison in this manner:
<?php
$array = [
["data" => "789"],
["data" => "800"],
["data" => "789"],
["data" => "787"],
["data" => "787"],
["data" => "789"],
["data" => "787"],
["data" => "787"],
];
// MAKE A COPY OF THE ORIGINAL ARRAY:
$arrayCopy = $array;
// POP THE LAST ELEMENT OFF THE $arrayCopy AND SAVE IT AS $lastElem:
$lastElem = array_pop($arrayCopy);
// POP THE LAST ELEMENT OFF THE $arrayCopy AGAIN AND SAVE IT AS $beforeLastElem:
$beforeLastElem = array_pop($arrayCopy);
// NOW YOU CAN COMPARE THE LAST ELEMENT AND THE ONE BEFORE IT
if($lastElem == $beforeLastElem){
echo "The last 2 Elements of \$array are the same";
}else{
echo "The last 2 Elements of \$array are not identical.";
}

Categories