I
I
ILoveYAnny2017-04-22 23:03:23
PHP
ILoveYAnny, 2017-04-22 23:03:23

How to sort a multidimensional array algorithm by a specific algorithm?

Hello, I have a multidimensional array with one flag parameter

array(
  array(
    "free"=>"0",
    "id"=>"86"
  ),
  array(
    "free"=>"0",
    "id"=>"23"
  ),
  array(
    "free"=>"0",
    "id"=>"23"
  ),
  array(
    "free"=>"1",
    "id"=>"23"
  ),
  array(
    "free"=>"1",
    "id"=>"43"
  ),
  array(
    "free"=>"1",
    "id"=>"54"
  ),
  array(
    "free"=>"1",
    "id"=>"65"
  )
  array(
    "free"=>"1",
    "id"=>"34"
  )
  array(
    "free"=>"1",
    "id"=>"32"
  )
)

I need to swap the arrays so that it would turn out
free=1
free=1
free=0
free=1
free=1
free=0
That is, it should turn out that two free flags, one paid. It should turn out like this
<?php
array(
    array(
    "free"=>"1",
    "id"=>"86"
  ),
  array(
    "free"=>"1",
    "id"=>"23"
  ),
  array(
    "free"=>"0",
    "id"=>"65"
  )
    array(
    "free"=>"1",
    "id"=>"23"
  ),
  array(
    "free"=>"1",
    "id"=>"23"
  ),
  array(
    "free"=>"0",
    "id"=>"34"
  )
  array(
    "free"=>"1",
    "id"=>"43"
  ),
  array(
    "free"=>"1",
    "id"=>"54"
  ),	
  array(
    "free"=>"0",
    "id"=>"32"
  )						
)

I can't imagine how to do it right, except to invent terrible bicycles and crutches ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stalker_RED, 2017-04-23
@ILoveYAnny

$result = $free0 = $free1 = [];
foreach($data as $d) { // разделяем на два массива
  if ($d['free']) {
    $free1[] = $d;
  } else {
    $free0[] = $d;
  }
}

while(!empty($free1) || !empty($free0)) { // объединяем в нужном соотношении
  if(!empty($free1)) $result[] = array_shift($free1);
  if(!empty($free1)) $result[] = array_shift($free1);
  if(!empty($free0)) $result[] = array_shift($free0);
}
sandbox.onlinephpfunctions.com/code/ab8d8873bb9057...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question