Working with an array

I have

Array
(
    [0] => Array
        (
            [beginning_ru] => 33.0
            [ending_ru] => 33.5
            [beginning_x] => 0.0
            [external_width] => 17.500
            [external_height] => 0.500
            [rack_mounting_direction] => Front
            [operational_status] => 1
        )

    [1] => Array
        (
            [beginning_ru] => 27.0
            [ending_ru] => 30.0
            [beginning_x] => 0.0
            [external_width] => 17.500
            [external_height] => 1.750
            [rack_mounting_direction] => Front
            [operational_status] => 1
        )

) 

am trying to create a new array from it using only the begining_ru and ending_ru keys.
like

Array
(
    [0] => Array
        (
            [beginning_ru] => 33.0
            [ending_ru] => 33.5
        )

    [1] => Array
        (
            [beginning_ru] => 27.0
            [ending_ru] => 30.0
        )

) 

Why? Can’t you just ignore all keys you don’t need?

6 Likes

Unless you’re pulling absolutely massive amounts of records (where size-in-memory becomes a concern), @rpkamp is 100% correct, there’s no mechanical benefit to doing this.

2 Likes

What if he wants to save the array as JSON and does not need the other data?

  1. Why doesn’t the data already just have the items you want, from whatever the query/code is that’s getting the data?
  2. As already asked, why can’t you just ignore the extra items?
  3. If you cannot do items #1 or #2 on this list, I would write a call-back function to just keep the array keys you want (see array_intersect_key()) and apply it to all the sub-arrays in the data using array_map().
1 Like

your right, ill use the existing array and ignore the other keys.

1 Like

the second one seems good
I want the function to run when a form is submitted though

<form...  onSubmit="detectCollision(frontAssets)">
...
</form>
...
// just have the function return true or false
function detectCollision(assets = []) {    
  const selectValue	= document.getElementById('Beginning_ru').value;

  return assets.some((asset) => selectValue > asset['beginning_ru'])
}z

if (detectCollision(frontAssets)) {
  document.getElementById('Collision').scrollIntoView()
}

Should I put the if statement inside the function?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.